Reputation: 113975
I'm a python guy and have recently started a C# project. One part of my code takes a myList = List<double[][]>
and needs to turn it into a myNewList = List<double[]>
to pass to another function.
So suppose myList
looks like this:
{{{0.0, 1.0}, {2.0, 3.0}}, {{4.0, 5.0}, {6.0, 7.0}}}
I want myNewList
to look like this:
{{0.0, 1.0}, {2.0, 3.0}, {4.0, 5.0}, {6.0, 7.0}}
In python, I would do this:
myNewList = list(itertools.chain.from_iterable(myList))
Now, I can very easily implement this with a foreach
loop and keep Add
ing to myNewList
, but does anyone know of a built-in way to do this?
Upvotes: 1
Views: 117
Reputation: 63327
better use LINQ
:
var myNewList = myList.SelectMany(x=>x).ToList();
Upvotes: 5
Reputation: 48096
You can use the method SelectMany
to "flatten" lists. Basically if you have a list of lists, it will concatenate all the lists into one. In this case you have a List<double[][]>
so it's nested three times.
List<double[]> flattenedList = myList.SelectMany(x => x.Select(y => y).ToArray()).ToList();
Will do it for you. The first Select
doesn't really do anything, I like to think of it like it's a for loop, read it as "for each x do x.SelectMany" it's needed to get down one layer to the double[][]
elements since those are really what you're flattening.
Upvotes: 2
Reputation: 8868
Try this:
myNewList.SelectMany(x => x.Select(y => y).ToArray()).ToList();
This will give you a List<double[]>
.
Upvotes: 4