拼合在C#锯齿状数组 [英] Flatten jagged array in C#
本文介绍了拼合在C#锯齿状数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有拉平在C#中的二维数组(使用LINQ与否)优雅的方式?
Is there an elegant way to flatten a 2D array in C# (using Linq or not)?
例如。假设
var my2dArray = new int[][] {
new int[] {1,2,3},
new int[] {4,5,6}
};
我想打电话给像
I want to call something like
my2dArray.flatten()
这将产生
{1,2,3,4,5,6}
任何想法
推荐答案
您可以使用的 的SelectMany
You can use SelectMany
var flat = my2dArray.SelectMany(a => a).ToArray();
这将交错数组就像你的榜样工作,但不能用二维数组像
This will work with a jagged array like in your example, but not with a 2D array like
var my2dArray = new [,] { { 1, 2, 3 }, { 1, 2, 3 } };
但在这种情况下,你可以遍历像这样
But in that case you can iterate the values like this
foreach(var item in my2dArray)
Console.WriteLine(item);
这篇关于拼合在C#锯齿状数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文