如何使用渐进索引从矩阵中获取值

本文关键字:获取 何使用 索引 | 更新日期: 2023-09-27 17:57:29

假设我有这个矩阵:

public static List<List<string>> WallPattern1550 = new List<List<string>>
{ 
    new List<string> { "3", "2", "1", "1", "2" },
    new List<string> { "1", "2", "2" },
    new List<string> { "2", "1", "2" },
    new List<string> { "2", "2", "1" },
    new List<string> { "2", "1", "1", "1" },
    new List<string> { "1", "2", "1", "1" },
    new List<string> { "1", "1", "2", "1" },
    new List<string> { "1", "1", "1", "2" }
};

我很快就想要16°的值(我指的是索引),即1(WallPattern1550[3][1]),我该怎么做?

我如何将16翻译成3.1?

如何使用渐进索引从矩阵中获取值

可以这样做:

WallPattern1550.SelectMany(x => x).Skip(15).First();

但就我个人而言,我会使用一种扩展方法:

public static T GetValueAt<T>(this List<List<T>> source, int index)
{
     int counter = 0;
     foreach(var list in source)
        foreach (var x in list)
        {
             counter++;
             if (counter == index) return x;
        }
     return default(T);
}

用法:

var value = WallPattern1550.GetValueAt(16);

如果你想在这里获得索引,你可以使用另一种扩展方法:

public static void FindCoordinates<T>(this IEnumerable<IEnumerable<T>> source, int count, out int x, out int y)
{
     x = 0;
     y = 0;
     int counter = 0;
     foreach (var list in source)
     {
         y = 0;
         foreach (var z in list)
         {
              if (counter == count) break;
              y++;
              counter++;
         }
         if (counter == count) break;
         x++;
     }    
}

用法:

int x, y;
WallPattern1550.FindCoordinates(16,out x, out y); // x = 4, y = 2