Example. In this program, we include the System.Linq namespace to get access to the Concat method. Two arrays are created upon execution of the Main method.
Then We call the Concat method twice, in different orders, and display the results.
Tip If you have ever needed to write custom code to combine two arrays or Lists into a single one, the Concat method might be useful.
using System;
using System.Collections.Generic;
using System.Linq;
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);
}dot
net
perls
!
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.
Much like string.Concat concatenates strings, the Concat extension concatenates collections. Whenever we need to combine two arrays into a third array, we use the Concat extension method.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 28, 2024 (edit).