How to use LINQ on a multidimensional array to 'unwind' the array?

南笙酒味 提交于 2019-11-27 02:46:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!