2012-12-06 83 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是指數。