linq 将多维数组转换为多维字典

cqoc49vn  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(184)

如何使用Lambda将一个int的多维数组转换为一个多维字典?
例如,我想将Test1(int[2,3])转换为Test 3(Dictionary〈(int,int),int〉)

int[,] Test1 = new int[2, 3];
    int k = 0;
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            Test1[i, j] = k++;
        }
    }

我可以很容易地将它转换成字典使用传统的方式与“for - next”循环,但当我尝试使用lambda:

Dictionary<(int,int),int>Test3 = Enumerable.Range(0, Test1.Length)
    .ToDictionary((int i ,int j )=>new { z =Test1[i, j] });

我得到了下面的语法错误:

Error   CS0411  The type arguments for method 'Enumerable.ToDictionary<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

如何显式指定类型参数?

iszxjhcz

iszxjhcz1#

不幸的是,你不能很容易地使用Linq来遍历二维数组的“行”,因为方形数组的迭代器只是遍历元素。你需要使用一个老式的for循环:

var Test3 = new Dictionary<(int,int),int>();

for (int i = 0; i < Test1.GetLength(0); i++)
{
    Test3[(Test1[i, 0], Test1[i, 1])] =  Test1[i, 2];
}

这假定前两个“列”中的对是唯一的,否则最后一个将“获胜”。
您 * 可以 * 使用Linq在一个轴上使用Range来枚举行,就像您尝试的那样:

Dictionary<(int,int),int>Test3 = Enumerable
    .Range(0, Test1.GetLength(0))
    .ToDictionary(i => (Test1[i, 0], Test1[i, 1]), i => Test1[i, 2]);

注意,ToDictionary中的lambda分别定义了键和值。
但是在我看来,for循环更干净,更容易理解。

相关问题