LINQ Append Method in C#:
The LINQ Append Method in C# is used to append a value to the end of the sequence. This method does not modify the elements of the sequence. Instead, it creates a copy of the sequence with the new appended element. If you go to the definition of the Append Method, then you will see the following signature.
- TSource:Â The data type of the elements contained in the sequence.
Parameters:
- IEnumerable<TSource> source:Â A sequence of values.
- TSource element:Â The value to append at the end of the sequence.
Returns:
- IEnumerable<TSource>:Â A new sequence that ends with the element.
Exceptions:Â When the source is null, it will throw ArgumentNullException.
Note:Â This method is supported by Framework 4.7.1 or later.
Example:
The following example shows how to use the Append Method to append a value to the end of the sequence. The following example is self-explained. So, please go through the comment lines.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using System.Linq; using System.Collections.Generic; using System; namespace LinqDemo { class Program { static void Main(string[] args) { // Creating a list of integer List<int> intSequence = new List<int> { 10, 20, 30, 40 }; // Trying to append 5 at the end of the intSequence intSequence.Append(5); //It doesn't work because the original list has not been changed Console.WriteLine(string.Join(", ", intSequence)); // It works now because we are using a changed copy of the original sequence Console.WriteLine(string.Join(", ", intSequence.Append(5))); // Creating a new sequence explicitly List<int> newintSequence = intSequence.Append(5).ToList(); // Printing the new sequence in the console Console.WriteLine(string.Join(", ", newintSequence)); Console.ReadKey(); } } } |
In the next article, I am going to discuss the LINQ Prepend Method in C# with examples. Here, in this article, I try to explain the LINQ Append Method with an example.
Leave a Comment