2013-07-15 21 views
0

的指數我的數據表,它的第一行標題 我根據頭LINQ數據行上得到具體項目

我知道如何讓列,如果知道它的索引需要特定的列此數據表。 的問題是如何得到該指數

Dim columnIndex as integer 
Dim headerRow As DataRow = dt.Rows(0) 
Dim colHeader As string ="abc" 
columnIndex=??? 
Dim result = dt.Rows.Cast(Of DataRow)().[Select](Function(row) row(columnIndex)).Distinct().ToList() 

感謝

回答

0

您可以使用dt.Rows.IndexOf

Dim ValueToSearch AS string = ... 
columnIndex = dt.AsEnumerable().Where(Function(x) x.Field(of String)(colHeader) = ValueToSearch).Select(Function(x) dt.Rows.IndexOf(x)).SingleOrDefault() 

如果WHERE子句只返回一個或零以上將工作行。如果這是不正確的,那麼你可以解散的SingleOrDefault然後通過結果循環,即:

columnIndex = dt.AsEnumerable().Where(Function(x) x.Field(of String)(colHeader) = ValueToSearch).Select(Function(x) dt.Rows.IndexOf(x)) 
For Each i in columnIndex 
    Console.WriteLine("Value found in row with index " + i.ToString()) 
Next 

Giannis