1

次のような「where句」を適用するコードがあります。

データベーステーブルの例として「n」を入れました。

List<KeyValuePair<int, int>> n = new List<KeyValuePair<int, int>>();
n.Add(new KeyValuePair<int, int>(1,2));
n.Add(new KeyValuePair<int, int>(1,3));
n.Add(new KeyValuePair<int, int>(4,6));
n.Add(new KeyValuePair<int, int>(4,3));
n.Add(new KeyValuePair<int, int>(5,3));

var zzz = n.Where(z => z.Key == 1); // this returns "1,2" and "1,3"

それから私のコードのどこかで私はこれをしました:

zzz.Where(x => x.Value == 3); // this should return "1,3"... Instead it seems to return "4,3" and "5,3" and "1,3".

2 番目の Where は "1,3" のみを返すはずではないですか? 2 番目の Where 句は、"zzz" の結果に適用する必要がありますね。

4

1 に答える 1

2

2 番目の Where 句は、"zzz" の結果に適用する必要がありますね。

はい、実際にそうです。次のサンプル コードを使用します。

List<KeyValuePair<int, int>> n = new List<KeyValuePair<int, int>>();
n.Add(new KeyValuePair<int, int>(1,2));
n.Add(new KeyValuePair<int, int>(1,3));
n.Add(new KeyValuePair<int, int>(4,6));
n.Add(new KeyValuePair<int, int>(4,3));
n.Add(new KeyValuePair<int, int>(5,3));

var zzz = n.Where(z => z.Key == 1); // this returns "1,2" and "1,3"

zzz = zzz.Where(x => x.Value == 3); // this then filters to the 2nd option

foreach(var pair in zzz)
    Console.WriteLine("{0}:{1}", pair.Key, pair.Value);

これは1:3、期待どおりに出力されます。

問題は、2 番目のフィルターの結果を再割り当てしていないことにあるとzzz.Where(x => x.Value == 3); 思われます。実際のフィルター処理された結果を表示するには、その結果を変数に割り当てる (または列挙する) 必要があります。

于 2013-10-09T18:42:22.633 に答える