
You have two Lists in your C# program and want to combine them one after the other. With the Concat extension method, you can do this without a loop. In this example, we take a look at the Concat method on Lists.

The Concat method is available in the System.Linq namespace in new versions of the .NET Framework. To use Concat, you can combine two collections that implement IEnumerable: this includes the List type or the array type. You can combine a List and an array or two Lists, as shown here. The element type (string) of both collections must be the same.
This C# program uses Concat to combine two List collections.
Program that uses Concat method on Lists [C#]
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<string> list1 = new List<string>();
list1.Add("dot");
list1.Add("net");
List<string> list2 = new List<string>();
list2.Add("perls");
list2.Add("!");
var result = list1.Concat(list2);
List<string> resultList = result.ToList();
foreach (var entry in resultList)
{
Console.WriteLine(entry);
}
}
}
Output
dot
net
perls
!
Converting back to List. The Concat method returns an IEnumerable type. The "var result" in the code is of that type. You can convert that back into a List with the ToList extension method.
ToList Extension MethodIf you have two Lists, you can use the Concat method to combine them. For optimal performance, however, using a method such as AddRange would be better if you need a List result. This is because you could avoid calling ToList. In many programs, though, the Concat method provides the best balance between simplicity and implementation.
Concat Extension Method Collections