for循环-如何在C#中遍历2D数组的每一个对角线



我有一个类型为int[5,6]的数组。:

   abcdef
   bcdefg
   cdefgh
   defghi
   efghij

我想把这些值加起来,比如:myArray[1,2]+ myArray[2,1]myArray[1,3]+ myArray[2,2]+ myArray[3,1]

我该如何以这种方式进行:

a
bb
ccc
dddd
eeeee
ffffff
ggggggg

等等

通用解决方案

public static IList<IList<T>> GetSecondaryDiagonals<T>(this T[,] array2d)
{
    int rows = array2d.GetLength(0);
    int columns = array2d.GetLength(1);
    var result = new List<IList<T>>();            
    // number of secondary diagonals
    int d = rows + columns - 1;
    int r, c;
    // go through each diagonal
    for (int i = 0; i < d; i++)
    {
        // row to start
        if (i < columns)
            r = 0;
        else
            r = i - columns + 1;
        // column to start
        if (i < columns)
            c = i;
        else
            c = columns - 1;
        // items from diagonal
        var diagonalItems = new List<T>();
        do
        {
            diagonalItems.Add(array2d[r, c]);
            r++;
            c--;
        } 
        while (r < rows && c >= 0);
        result.Add(diagonalItems);
    }
    return result;
}

使用示例

private static void Main()
{
    var T1 = new char[,] // more rows than columns
        {
            {'a', 'b', 'd'},
            {'c', 'e', 'g'},
            {'f', 'h', 'j'},
            {'i', 'k', 'l'},
        };
    var T2 = new int[,] // more columns than rows
        {
            {1, 2, 4, 7},
            {3, 5, 8, 0},
            {6, 9, 1, 2},
        };
    Print(T1.GetSecondaryDiagonals());
    Print(T2.GetSecondaryDiagonals());
    Console.ReadKey();
}
static void Print<T> (IList<IList<T>> list)
{
    Console.WriteLine();
    foreach (var sublist in list)
    {
        foreach (var item in sublist)
        {
            Console.Write(item);
            Console.Write(' ');
        }
        Console.WriteLine();
    }
}

输出

a
b c
d e f
g h i
j k
l
1
2 3
4 5 6
7 8 9
0 1
2

最新更新