Tuesday, March 15, 2011

Refactoring my DataTable search code

I am using C# 2.0, and I can't help but think this isn't the most efficient way to search a collection (in this case a DataTable) for a value:

bool found = false;
foreach (DataRow row in data.Rows)
{
    if (id == row["rowID"])
    {
        found = true;
        break;
    }
}
if (!found)
{
    //Do stuff here
}

Can anyone think of a "cleaner" way to do this?

From stackoverflow
  • Look at the datatable's Select() method:

    http://msdn.microsoft.com/en-us/library/b5c0xc84(VS.80).aspx

    DataRow[] rows = data.Select("rowID=" + id.ToString());
    if (rows.Length > 0)
    {
        //Do stuff here
    }
    
    Jon Tackabury : Thanks - 1 line works for me. :)
  • This is a linear search and it is the slowest actual search there is.

    One alternative, if you want to continue using a DataTable, is to define a primary key and use the Find() method:

    myTable.PrimaryKey = new DataColumn[] { new DataColumn("rowID") };
    DataRow row = myTable.Find(id);
    

0 comments:

Post a Comment