实现IEnumerable锯齿状数组,该数组返回转置项

时间:2018-08-16 14:43:10

标签: c# linq matrix transpose ienumerator

我自己尝试过做,这真是令人头疼...

我希望能够使用LINQ从SelectT[key1][key2],实际上它在这里“看到” T[key2][key1](即转置矩阵)。我想这样做的原因是,我不必手动转置数组项(这很慢),而是即时提供转置的数组项。

不确定这是否有可能!

编辑:添加此功能的示例:

T[][]T[,] .Select(item => item),其中item类型为T[],是第N个枚举数位置的集合。

int[,] matrix = new int[2,2] {{1, 2}, {3, 4}};
matrix = matrix.Select(item => item); //Where .Select magically transposes
//Matrix is now {{1, 3}, {2, 4}}

2 个答案:

答案 0 :(得分:1)

要编写代码以换位顺序遍历数组,您只需编写代码即可正常遍历数组; IEnumerable的数组实现使用什么,但是不必遍历外循环中的最低维度和内循环中的较高维度,只需反转它们即可:

public static IEnumerable<T> TraverseTransposed<T>(this T[,] array)
{
    for (int j = 0; j < array.GetLength(1); j++)
        for (int i = 0; i < array.GetLength(0); i++)
            yield return array[i, j];
}

答案 1 :(得分:0)

这是您的意思吗(慢吗?):

var items = new int[,] {
   {1,2,3,4,5,6},
   {10,20,30,40,50,60},
   {100,200,300,400,500,600},
};  

var transposed = new int[items.GetLength(1), items.GetLength(0)];

for (int row = 0; row < items.GetLength(0); row++)
{
    for (int col = 0; col < items.GetLength(1); col++)
    {
       transposed[col,row]  = items[row,col];
    }
}
相关问题