Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through a DataTable to find elements in a List object?

As I iterate through a DataTable object, I need to check each of its DataRow objects against the items in a generic string List.

I found a blog post using the List's Find method along with a delegate, but whereas that example has a separate class (Person), I'm attempting something like the following using an instance of the string object:

// My definition of the List object.
List<string> lstAccountNumbers = new List<string>();
...

// I populate the List via its Add method.
...

foreach (DataRow drCurrentRow in dtMyDataTable.Rows) 
{
    if (lstAccounts.Find(delegate(string sAccountNumber) { return sAccountNumber == drCurrentRow["AccountNumber"]; })
    {
        Found_DoSomething();
    }
    else
    {
        NotFound_DoSomethingElse();
    }
}

However, with this syntax I'm receiving "Cannot implicitly convert type 'string' to 'bool'" for the if block.

Could someone please clarify what I'm doing wrong and how best to accomplish what I'm trying to do?

like image 887
Darth Continent Avatar asked Mar 24 '10 15:03

Darth Continent


3 Answers

Same Delegate Different method. You want to use Exists Not Find. Find Returns a value while exists returns a bool.

if (lstAccounts.Exists(delegate(string sAccountNumber) { return sAccountNumber == drCurrentRow["AccountNumber"]; })
like image 184
Anthony Avatar answered Nov 01 '22 04:11

Anthony


why would not this work for you?

foreach (DataRow drCurrentRow in dtMyDataTable.Rows) 
{
    if (lstAccounts.Contains(drCurrentRow["AccountNumber"].ToString()))
    {
        Found_DoSomething();
    }
    else
    {
        NotFound_DoSomethingElse();
    }
}
like image 1
Luiscencio Avatar answered Nov 01 '22 04:11

Luiscencio


The problem is the if (lstAccounts.Find part.

This Find will return a string if found and the if is expecting a bool output.

Change your statement to use Exists or compare your original value to the Find result.

like image 1
Kelsey Avatar answered Nov 01 '22 04:11

Kelsey