2016-10-13 6 views
0

に囲まれているにCheckedListBoxを検索:私はデータテーブルにバインドされたデータとにCheckedListBox(リサイズ)を持っているデータテーブル使用してLINQ

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

今、私は特定の顧客IDのにCheckedListBoxを検索したいですその行を選択します。私は次のように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); 
+0

この行は次のようになります:int index = clbCustomer.Items.Cast ().Where(x => x ["customerId"] == 255);まったくコンパイルできますか?ここに返された結果はコレクションだと思われます。だから、FirstorDefaultを追加して修正できますか?私が間違っているなら、私を訂正してください。 –

+0

ありがとうございます。いいえ、その行はまったく機能しません。それは私がどのように修正するかわからないものです。 –

+0

var index = clbCustomer.Items.Cast ().Where(x => x ["customerId"] == 255).FirstOrDefaut(); clbCustomer.SetItemChecked(index.customerId、true);おそらく役に立ちます=) –

答えて

2

のLINQ文がコレクションを返します。あなたが使用する場合

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

それはあなたのコレクションの代わりにあなたの単一のアイテムを得るでしょう。その後、

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

を呼び出すことで、このアイテムのインデックスを取得できます。

+1

答えは以下のように見えます。それらを見つけた=) –

+0

それはキース良い仕事でした!答えを更新する場合は、ちょうど1回微調整してください:var item = clbCustomer.Items.Cast ().Where(x => Convert.ToInt32(x ["customerId"])== 255).FirstOrDefault(); –

+0

@RobertSmith @RobertSmithは私の答えを更新してくれてうれしく思います。 – Keithin8a

関連する問題