Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> Concatenation for 'X' amount of lists

I have for example 5 List all of the same type. Can I simply do

List<T> newset = List1.Concat(List2).Concat(List3).Concat(List4).....
like image 836
Jon Avatar asked Mar 01 '10 17:03

Jon


2 Answers

You can do this (although you need .ToList() at the end).

However, it would be (slightly) more efficient to generate a single list, and use AddRange to add in each list. Just initialize the list with the total size of all of your lists, then call AddRange repeatedly.

You might want to consider doing something like:

public List<T> ConcatMultiple<T>(this List<T> list, params[] ICollection<T> others)
{
    List<T> results = new List<T>(list.Count + others.Sum(i => i.Count));
    results.AddRange(list);
    foreach(var l in others)
        results.AddRange(l);
    return results;
}

Then calling via:

List<MyClass> newset = List1.ConcatMultiple(List2, List3, List4);
like image 81
Reed Copsey Avatar answered Oct 05 '22 03:10

Reed Copsey


Yes, you can do that.

List<Thing> newSet = List1.Concat(List2).Concat(List3).Concat(List4).ToList();
like image 28
David Morton Avatar answered Oct 05 '22 03:10

David Morton