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

时间:2014-04-08 15:06:06

标签: c# .net list matrix

假设我有这个矩阵:

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?

1 个答案:

答案 0 :(得分:3)

可以这样做:

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