Say I have an arbitrary number of collections, each containing objects of the same type (for example, List
and List
).
Use Enumerable.Concact:
var query = foo.Concat(bar);
Use Enumerable.Concat like so:
var combined = foo.Concat(bar).Concat(baz)....;
A couple techniques using Collection Initializers --
assuming these lists:
var list1 = new List<int> { 1, 2, 3 };
var list2 = new List<int> { 4, 5, 6 };
SelectMany
with an array initializer (not really that elegant to me, but doesn't rely on any helper function):
var combined = new []{ list1, list2 }.SelectMany(x => x);
Define a list extension for Add which allows IEnumerable<T>
in the List<T>
initializer:
public static class CollectionExtensions
{
public static void Add<T>(this ICollection<T> collection, IEnumerable<T> items)
{
foreach (var item in items) collection.Add(item);
}
}
Then you can create a new list containing the elements of the others like this (it also allows single items to be mixed in).
var combined = new List<int> { list1, list2, 7, 8 };
You could always use Aggregate combined with Concat...
var listOfLists = new List<List<int>>
{
new List<int> {1, 2, 3, 4},
new List<int> {5, 6, 7, 8},
new List<int> {9, 10}
};
IEnumerable<int> combined = new List<int>();
combined = listOfLists.Aggregate(combined, (current, list) => current.Concat(list)).ToList();
The only way I see is to use Concat()
var foo = new List<int> { 1, 2, 3 };
var bar = new List<int> { 4, 5, 6 };
var tor = new List<int> { 7, 8, 9 };
var result = foo.Concat(bar).Concat(tor);
But you should decide what is better:
var result = Combine(foo, bar, tor);
or
var result = foo.Concat(bar).Concat(tor);
One point why Concat()
will be a better choice is that it will be more obvious for another developer. More readable and simple.