我声明了一个 3 X 3 矩阵
int[,] matrix=new int[3,3]
{
{1,2,3},
{4,5,6},
{11,34,56}
};
当我尝试像这样枚举它时
var diagonal = matrix.AsQueryable().Select();
我无法将其转换为可枚举集合。该怎么做?
最佳答案
矩形数组不实现通用 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);
}
}
}
输出:
1
4
9
16
25
36
121
1156
3136
关于C# LINQ 无法枚举矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3607321/