1

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

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?

user1570048
  • 880
  • 6
  • 35
  • 69
  • 2
    There are certainly different ways to achieve the same result. But this one is probably the fastest. Some Indexing might help, depends on your dataset. – Sam Axe Feb 08 '13 at 19:04
  • 1
    I agree with Dan-o, you also could change the `If mtable.Rows(i)("x") = 2 Then` to the column Index of `x` column, for sample: `If mtable.Rows(i)(2) = 2 Then` – Felipe Oriani Feb 08 '13 at 19:10
  • 1
    I'd initialize rowIndex to -1 so that you can tell if the value wasn't found. – Andrew Morton Feb 08 '13 at 19:21
  • Possible duplicate: http://stackoverflow.com/questions/12386827/datatable-how-to-get-item-value-with-row-name-and-column-name-vb – mas_oz2k1 May 14 '14 at 04:01

2 Answers2

2

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

    var index = mtable.Rows.IndexOf(mtable.Select("x = 2").FirstOrDefault());
DotNetUser
  • 6,494
  • 1
  • 25
  • 27
1

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:

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.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • No more than 200 records, code in question is still fine but can it get faster with hash table mapping? – user1570048 Feb 08 '13 at 21:55
  • @user1570048 If that's all the records you have, then if speed is a problem it might be worth considering that the problem is elsewhere. – Andrew Morton Feb 08 '13 at 22:30