How to Combine Values of Several Lists into One in C#

How to combine values of several lists into one in C#?

You can also use LINQ functions.

var listA = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var listB = new List<string> { "A", "B", "C", "D" };
var listC = new List<string> { "!", "?", "-" };

var result = Enumerable.Range(0, Math.Max(Math.Max(listA.Count, listB.Count), listC.Count))
.Select(i => new
{
a = listA.ElementAtOrDefault(i),
b = listB.ElementAtOrDefault(i),
c = listC.ElementAtOrDefault(i)
}).ToList();

foreach (var item in result)
{
Console.WriteLine("{0} {1} {2}", item.a, item.b, item.c);
}

Result:

1 A !
2 B ?
3 C -
4 D
5
6
7
8
9

Joining two lists together

You could try:

List<string> a = new List<string>();
List<string> b = new List<string>();

a.AddRange(b);

MSDN page for AddRange

This preserves the order of the lists, but it doesn't remove any duplicates which Union would do.

This does change list a. If you wanted to preserve the original lists then you should use Concat (as pointed out in the other answers):

var newList = a.Concat(b);

This returns an IEnumerable as long as a is not null.



Related Topics



Leave a reply



Submit