问题
Consider the following array:
int[,] numbers = new int[3, 2] { { 2, 1 }, { 3, 4 }, { 6, 5 } };
I would like to use LINQ to construct an IEnumerable with numbers 2, 1, 3, 4, 6, 5.
What would be the best way to do so?
回答1:
How about:
Enumerable
.Range(0,numbers.GetUpperBound(0)+1)
.SelectMany(x => Enumerable.Range(0,numbers.GetUpperBound(1)+1)
.Select (y =>numbers[x,y] ));
or to neaten up.
var xLimit=Enumerable.Range(0,numbers.GetUpperBound(0)+1);
var yLimit=Enumerable.Range(0,numbers.GetUpperBound(1)+1);
var result = xLimit.SelectMany(x=> yLimit.Select(y => numbers[x,y]));
EDIT Revised Question....
var result = array.SelectMany(x => x.C);
回答2:
Perhaps simply:
var all = numbers.Cast<int>();
Demo
回答3:
Use simple foreach to get your numbers from 2d array:
int[,] numbers = new int[3, 2] { { 2, 1 }, { 3, 4 }, { 6, 5 } };
foreach(int x in numbers)
{
// 2, 1, 3, 4, 6, 5.
}
LINQ (it's an big overhead to use Linq for your initial task, because instead of simple iterating array, CastIterator (Tim's answer) of OfTypeIterator will be created)
IEnumerable<int> query = numbers.OfType<int>();
来源:https://stackoverflow.com/questions/13822750/how-to-use-linq-on-a-multidimensional-array-to-unwind-the-array