简体   繁体   中英

Search a CheckedListBox that is bounded to a datatable using linq

I have a CheckedListBox (winforms) with data that is bounded to a datatable:

clbCustomer.DataSource = ds.Tables["Default"];
clbCustomer.DisplayMember = "desc";
clbCustomer.ValueMember = "customerId";

Now I would like to search the checkedlistbox for a particular customer id and then select that row. I can do this with a foreach statement as follows:

// Find the index
int index = 0;
foreach (DataRowView item in clbCustomer.Items)
{
    int cusId = Convert.ToInt32(item["customerId"]);
    if (cusId == 255)
    {
        break;
    }
    index++;
}
// Select the customer
clbCustomer.SetItemChecked(index, true);

However, it seems very bulky to do it this way. I am attempting to convert the above code into linq but have not been able to accomplish it. Here is what I have so far:

// Find the index (not working)
int index = clbCustomer.Items.Cast<DataRowView>().Where(x => x["customerId"] == 255);
// Select the customer
clbCustomer.SetItemChecked(index, true);

But not sure how to extract the index of that customer id using linq. Any help would be appreciated. Thanks.

Solution provided by Keithin8a below:

var item = clbCustomer.Items.Cast<DataRowView>().Where(x => Convert.ToInt32(x["customerId"]) == 255).FirstOrDefault();

int index = clbCustomer.Items.IndexOf(item);

Linq statements like that return a collection as mentioned in the comments. If you were to use

var item = clbCustomer.Items.Cast<DataRowView>().Where(x => Convert.ToInt32(x["customerId"]) == 255).FirstOrDefault()

That would get you your a single item instead of a collection. You can then get the index of this item by calling

int index = clbCustomer.Items.IndexOf(item);

That should get you what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM