【问题标题】:linq on datarow to get index of specific itemlinq on datarow 获取特定项目的索引
【发布时间】:2013-07-15 08:13:58
【问题描述】:
我有第一行是标题的数据表
根据标题,我需要此数据表的特定列
如果知道它的索引,我知道如何获取该列。
问题是如何获取索引
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()
谢谢
【问题讨论】:
标签:
linq
datatable
datarow
【解决方案1】:
您可以使用 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
詹尼斯