簡體   English   中英

使用linq搜索綁定到數據表的CheckedListBox

[英]Search a CheckedListBox that is bounded to a datatable using linq

我有一個CheckedListBox(winforms),其數據綁定到數據表:

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

現在,我想在復選框列表中搜索特定的客戶ID,然后選擇該行。 我可以使用如下的foreach語句來做到這一點:

// 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);

但是,以這種方式執行此操作似乎非常龐大。 我正在嘗試將上面的代碼轉換為linq,但無法完成。 這是我到目前為止的內容:

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

但不確定如何使用linq提取該客戶ID的索引。 任何幫助,將不勝感激。 謝謝。

Keithin8a提供的解決方案如下:

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

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

像這樣的Linq語句返回注釋中提到的集合。 如果您要使用

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

那將使您得到一個項目而不是一個集合。 然后,您可以通過調用以下內容獲取該項目的索引

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

那應該給您您想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM