I have been struggling with a problem all afternoon and I was hoping someone could help me out. I am using vb.net and asp.net.
I have an ArrayList containing 2 elements. I also have a DataTable with many DataRows. I want to create a new DataTable which contains the 2 DataRows that match the 2 elements in the ArrayList. The first item in each row contains the column that I want to compare the ArrayList against. I am looking for speed since the original DataTable can be large. Is there a quick way to do this? I hope this makes sense.
Thanks in advance!
Bo
Seehttp://forums.asp.net/1071268/ShowPost.aspx
See if this works for you.
' The name of the column in the DataTable to compare...
Dim compareColumnName As String = "compare-column-name-here"
' Clone the original, getting structure only...
Dim newDataTable As DataTable = originalDataTable.Clone()
Dim i As Integer
For i = 0 To valuesArrayList.Count - 1
' The value to compare...
Dim compareValue As String = CStr(valuesArrayList(i))
' Build a filter statement...
Dim sqlFilter As String = String.Format("{0} = '{1}'", compareColumnName, compareValue)
' Execute the filter...
Dim dataRowArray As DataRow() = originalDataTable.Select(sqlFilter)
' If we find a row, add it to the new DataTable...
If dataRowArray.Length > 0 Then
newDataTable.ImportRow(dataRowArray(0))
End If
Next i
NC...
bobh0526--
Regarding this...
bobh0526 wrote:
...I have an ArrayList containing 2 elements. I also have a DataTable with many DataRows. I want to create a new DataTable which contains the 2 DataRows that match the 2 elements in the ArrayList. The first item in each row contains the column that I want to compare the ArrayList against. I am looking for speed since the original DataTable can be large. Is there a quick way to do this?...
...off the top of my head, I can say...
...it, unfortunately, looks like you may have to loop...
...loops are, by nature, expensive and therefore take a lot of time...
...you may want to try to make one of the columns in the DataTable a primary key column, and then use a DataView and simply filter on the key... that MIGHT be quicker than a straight loop, but I do not know...
...however, if you can somehow use a HashTable rather than DataTable, that might help too because seeking for a hashed key is a lot faster than looping... so you would have the HashTable with just the data you need, as few columns as possible... and then you would have a key on these rows in the HashTable to be the data that you will be seeking... then you would have that actual key that you want to find in the ArrayList... grab the key from the ArrayList... seach on that key against the HashTable... and the data should be found fast... but, you may have to deal with the HashTable in some strange way so that it can hold the data you need... that is something you have to figure out... the point to note is that seeking over a hashed key (such as in HashTable) is very fast...
HTH.
0 comments:
Post a Comment