1

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 Adding to myNewList, but does anyone know of a built-in way to do this?

4

3 回答 3

5

better use LINQ:

var myNewList = myList.SelectMany(x=>x).ToList();
于 2013-08-30T16:34:19.617 回答
4

Try this:

myNewList.SelectMany(x => x.Select(y => y).ToArray()).ToList();

This will give you a List<double[]>.

于 2013-08-30T16:42:55.060 回答
2

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.

于 2013-08-30T16:40:02.010 回答