TheDeveloperBlog.com


C# List Concat

List Concat. Two Lists can be combined. With the Concat extension method, we do this without a loop. Concat is located in the System.Linq namespace. In this example we examine the Concat method on Lists.


Example. 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.

Also: You can combine a List and an array or two Lists. The element type (string) of both collections must be the same.

C# program that uses Concat method on Lists

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

Summary. If 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.

But: In many programs the Concat method provides the best balance between simplicity and implementation.

Concat