我宣布了3 X 3矩阵
int[,] matrix=new int[3,3]
{
{1,2,3},
{4,5,6},
{11,34,56}
};
Run Code Online (Sandbox Code Playgroud)
当我试图枚举它时
var diagonal = matrix.AsQueryable().Select();
Run Code Online (Sandbox Code Playgroud)
我很难将它转换为可枚举的集合.如何做到这一点?
矩形数组不实现泛型IEnumerable<T>类型,因此您需要调用Cast<>.例如:
using System;
using System.Collections.Generic;
using System.Linq;
class Test
{
static void Main()
{
int[,] matrix=new int[3,3]
{
{1,2,3},
{4,5,6},
{11,34,56}
};
IEnumerable<int> values = matrix.Cast<int>()
.Select(x => x * x);
foreach (int x in values)
{
Console.WriteLine(x);
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
1
4
9
16
25
36
121
1156
3136
Run Code Online (Sandbox Code Playgroud)