DataView or foreach

  • Thread starter Thread starter Ondrej Sevecek
  • Start date Start date
O

Ondrej Sevecek

Hello,
I would like to find DataRow from some table identified by IDENTITY column
value:

foreach (DataRow currentRow in DataTable1)
{
if (currentRow["identitycolumn"] == 100)
{
break;
}


--or--

new DataView(DataTable1, "identitycolumn = 100", null, ...



What method is more efficient and how can one determine the efficiency of
such different methods in other cases?

Ondra.
 
Hi,

If you have a primary key defined on that column you might use
DataRow targetRow = DataTable1.Rows.Find(100);

If I had to chose between options below I would go with foreach since
DataView has probably some overhead.
 
Depending on what your ultimate objective is, I'd either use the Find method
like Miha suggests, or use the RowFilter property. I think your
implementation is slower in the first case, but you could improve it by
using Index based lookups instead of nominal ones (ie currrentRowp[0] vs
currentRow["identitycolumn"])

If you don't have a PK, the second method isn't going to work so you'd have
to use the first or use the RowFilter method, so that's also a variable in
the equation, b/c even in this instance where you may have a key, you may
not always have one - so the 'better' method can be relative.

With all that said, I haven't run any performance traces, but I really doubt
the first method would be faster in most instances, but even if it were,
using Find is much cleaner and more readable (if you did this in say 300
instances in your code where you app had a lot of different searches, you'd
save yourself 600 lines of code....

HTH,

Bill
 
Hi Ondrej,

If it's not the PK, use a dataview and the find method. The problem with
for each is that it has no idea how many rows it has to traverse before it
finds what it wants, whereas the dataview find method with scan based on an
existing or generated index.

HTH,

Bernie Yaeger
 
Back
Top