2012-12-06 101 views
0

我需要模拟矩阵的数据和Im使用List<List <string >>。 Im使用IndexOf来搜索列表中的元素。矩阵与列表<列表<string >>索引

Matrix[0].IndexOf('Search'); 

但有可能使一种IndexOfMatrix

+0

index传统上返回单个数字。这样的功能在二维矩阵上是没有意义的。让我们说你想要一个位置返回列表的索引,然后是列表中的字符串的索引,你可以编写自己的扩展方法,它循环遍历列表,然后执行和索引以给你想要的结果。 – ryadavilli

回答

0
for(int i = 0; i<Matrix.Length; i++) 
    for(int j = 0; j<Matrix.Length; j++) 
     if(Matrix[i][j] == "Search") 
     { 
      //OUT i,j; 
      return; 
     } 
1

你必须让自己的班级来实现它。

public class Matrix<T> 
{ 
    public void IndexOf<T>(T value, out int x, out int y){...} 
} 

或使用你的类型的扩展

public static void IndexOf<T>(this List<List<T>> list, out int x, out int y){...} 

就个人而言,我会成为一个二维阵列上,而不是List<List<T>>扩展。如果您想了解该列中进行搜索,搜索的行索引

int index = Matrix.FindIndex(x => x[colIndex] == "Search"); 

这种方法显然是非常有益

如果你想在全搜索:

+0

嗯,你可以做一个帮手/扩展方法而不是整个班级。 – Rawling

+0

@Rawling在发表评论时输入了语法 –

+1

可能返回Tuple 而不是使用params。 – juharr

2

你可以使用FindIndex方法。矩阵你可以写一个简单的方法:

public static Tuple<int,int> PositionOf<T>(this List<List<T>> matrix, T toSearch) 
{ 
    for (int i = 0; i < matrix.Count; i++) 
    { 
     int colIndex = matrix[i].IndexOf(toSearch); 
     if (colIndex >= 0 && colIndex < matrix[i].Count) 
      return Tuple.Create(i, colIndex); 
    } 
    return Tuple.Create(-1, -1); 
} 
0

可能都在问类似:

public void MatrixIndexOf(string content) { 
     var result = matrix.Select((value, index)=> new { 
     _i = index, 
     _str = value 
     }).Where(x=>x._str.Contains(content)); 
} 

result后是匿名的类型,其中_i是指数。