vb.net 如果某个列值等于某值,则获取行索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14779521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:16:15  来源:igfitidea点击:

Get row index if some column value is equal to something

vb.netdatatable

提问by user1570048

In this datatable there are no duplicates, I need the row index where column x value equals 2. I would do it like this:

在此数据表中没有重复项,我需要列 x 值等于 2 的行索引。我会这样做:

Dim rowIndex As Integer = 0
For i = 0 To mtable.Rows.Count - 1
            If mtable.Rows(i)("x") = 2 Then
                rowIndex = i
                Exit For
            End If
        Next

I will be calling this process multiple times per second. Is there a faster way to do this in .NET?

我将每秒多次调用此过程。在 .NET 中是否有更快的方法来做到这一点?

采纳答案by Andrew Morton

Multiple times per second is a bit vague - tens or thousands?

每秒多次有点模糊 - 数万或数千?

You could create a hash table mapping the value of "x" to the row number:

您可以创建一个哈希表,将“x”的值映射到行号:

Dim nLookups = mtable.Rows.Count - 1
Dim lookupHash As New Hashtable(nLookups)
For i = 0 To nLookups
    lookupHash.Add(CInt(mtable.Rows(i)("x")), i)
Next

then

然后

Dim rowSought As Integer = -1
If lookupHash.ContainsKey(2) Then
    rowSought = lookupHash(2)
End If

Or if the range of possible values of "x" is suitable, you could use an array to map the value to the row number.

或者,如果“x”的可能值范围合适,您可以使用数组将值映射到行号。

回答by DotNetUser

DataTable select could work, i think it should be faster than iterating over the collection of rows.

DataTable select 可以工作,我认为它应该比迭代行集合更快。

    var index = mtable.Rows.IndexOf(mtable.Select("x = 2").FirstOrDefault());