Linq Append Method in C#

Introduction:

Linq (Language Integrated Query) is a powerful feature in C# that provides a unified way to access data from various sources. Linq allows you to query data from collections, arrays, databases, and XML files. It also provides several methods that make it easy to manipulate and transform data.

One such method is the Linq Append Method. The Append method is used to add elements to the end of a sequence. It is particularly useful when you want to add a single element to a sequence without creating a new sequence.

Syntax: The syntax for the Append method is as follows:

public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> source, TSource element);

Here, source is the input sequence to which you want to add an element, and element is the element that you want to add to the end of the sequence. The method returns a new sequence that contains the original elements plus the newly added element.

Example: Let’s see an example of how to use the Append method in C#:
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        var newNumbers = numbers.Append(6);

        foreach (var number in newNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

In this example, we have a list of integers called numbers with the values 1, 2, 3, 4, and 5. We then use the Append method to add the value 6 to the end of the list. We store the result in a new variable called newNumbers and iterate over it using a foreach loop to print out each number. The output of this program will be:

1
2
3
4
5
6

As you can see, the Append method has added the value 6 to the end of the original sequence.

Conclusion:

In conclusion, the Linq Append method is a useful tool for adding elements to a sequence in C#. It is a simple and efficient way to modify a sequence without creating a new one. By mastering this method, you can make your code more readable and maintainable, and save time by avoiding the need to create new sequences.