使用linq的selectmany方法可以将多维数组展平为一维序列。具体做法是先通过cast

如何将二维数组转为扁平的一维数组
直接对二维数组调用Cast和SelectMany即可得到结果。输入是一个int[,]类型的矩阵,输出是包含所有元素的int[]。代码中无需手动处理索引,LINQ会自动处理底层存储。

using System;
using System.Linq;
class Program {
static void Main() {
int[,] matrix = { { 1, 2 }, { 3, 4 } };
var flat = matrix.Cast<int>().ToArray();
Console.WriteLine(string.Join(", ", flat));
}
}</int>
预期输出:1, 2, 3, 4
如何自定义扁平化时的元素筛选条件
在SelectMany之前或之后加入Where条件可以过滤元素。例如只保留大于2的值。输入仍是二维数组,但输出仅包含满足条件的元素。这种写法保持了链式调用的简洁性,且不影响性能结构。

using System;
using System.Linq;
class Program {
static void Main() {
int[,] matrix = { { 1, 2 }, { 3, 4 } };
var filtered = matrix.Cast<int>()
.Where(x => x > 2)
.ToArray();
Console.WriteLine(string.Join(", ", filtered));
}
}</int>
预期输出:3, 4
当数组中包含null引用时会发生什么
如果多维数组是引用类型如string[,]且包含null值,Cast










