List <T> Concatenation for the number of elements "X"
I have, for example, 5 a list of all the same types. Can i just do
List<T> newset = List1.Concat(List2).Concat(List3).Concat(List4).....
you can, but don't forget to add .ToList();
in the end. also you can call newset.AddRange(ListX);
I think it's better in terms of performance
You can do this (although you need .ToList()
at the end).
However, it would be (slightly) more efficient to create a single list and use AddRange to add to each list. Just initialize the list with the total size of all your lists, then call AddRange again.
You might want to do 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 call through:
List<MyClass> newset = List1.ConcatMultiple(List2, List3, List4);
Yes you can do it.
List<Thing> newSet = List1.Concat(List2).Concat(List3).Concat(List4).ToList();
If you want to combine an arbitrary (previously unknown) number of lists, you may need to concatenate the collection of lists. Probably the easiest way would be to use the SelectMany
operator (or the nested from
clauses in the LINQ query):
IEnumerable<List<int>> lists = /* get list of lists */; List<int> result = lists.SelectMany(e => e).ToList();
The SelectMany
operator calls this function for each element of the input list (which is a list), and then combines all the resulting lists (actual lists from the list of input lists). Alternatively, using the LINQ query syntax:
List<int> result = (from l in lists from e in l select e).ToList();
I believe that the C # compiler can actually optimize this so that it does not iterate over all the individual elements (and does the same thing as the explicit version above). If you have a known number of lists, you can of course write:
List<int> result = (from l in new[] { list1, list2, list3, list4 } from e in l select e).ToList();
It is not as elegant as defining your own method specifically for this purpose, but it does show how strong the syntax of the LINQ query is.
You can of course do it, although it can be incredibly effective.
As indicated in other answers, be sure to add .ToList()
to the end of your line of code or use List1.AddRange(List2); List1.AddRange(List3); ...
List1.AddRange(List2); List1.AddRange(List3); ...
List1.AddRange(List2); List1.AddRange(List3); ...
to increase efficiency.
For a list of variable list:
IEnumerable<T> enumerable = Enumerable.Empty<T>(); foreach (List<T> list in [whatever]) enumerable = enumerable.Concat(list);
At the end, you can add "ToList ()" if you need a trust list:
List<T> list = enumerable.ToList();
However, this may not be indicated.
you can use a join in LINQ if it is the real join you want to make out of context ...