Reputation: 27
private static void A(){
List<int[]> list = new List<int[]>();
int[] a = {0,1,2,3,4};
int[] b = {5,6,7,8,9};
list.Add(a);
list.Add(b);
List<int> list2 = new List<int>();
// list2 should contain {0,1,2,3,4,5,6,7,8,9}
}
How would i convert my List<int[]> list
into a List<int>
so that all the int[] arrays
become one giant list of numbers
Upvotes: 0
Views: 384
Reputation: 13676
It looks like you might be looking for LINQ .SelectMany
method.
A quote from MSDN:
Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence
List<int> list2 = list.SelectMany(l => l).ToList();
If you want numbers to be ordered in a specific order you could use .OrderBy
before executing the query (which will be executed when we call .ToList
)
List<int> list2 = list.SelectMany(l => l).OrderBy(i => i).ToList();
Upvotes: 9
Reputation: 247
I would use the aggregate function. It is better when you have bigger collection.
List<int> list2 = list.Aggregate(new List<int>(), (ag, l) => { ag.AddRange(l); return ag; });
Upvotes: 0