2

次のようなコードがあります。

var dict = new Dictionary<string, IList<string>>();
dict.Add("A", new List<string>{"1","2","3"});
dict.Add("B", new List<string>{"2","4"});
dict.Add("C", new List<string>{"3","5","7"});
dict.Add("D", new List<string>{"8","5","7", "2"});

var categories = new List<string>{"A", "B"};

//This gives me categories and their items matching the category list
var result = dict.Where(x => categories.Contains(x.Key));

キー値
A 1、2、3
B 2、4

私が取得したいのはこれです:
A 2
B 2

したがって、両方のリストにあるキーと値だけです。LINQでこれを行う方法はありますか?

ありがとう。

4

2 に答える 2

1

簡単なピージー

string key1 = "A";
string key2 = "B";
var intersection = dict[key1].Intersect(dict[key2]);

一般に:

var intersection = 
    categories.Select(c => dict[c])
              .Aggregate((s1, s2) => s1.Intersect(s2));

ここでは、 を利用してEnumerable.Intersectいます。

于 2013-07-19T03:08:06.660 に答える
0

ちょっと汚いやり方…

var results = from c in categories
join d in dict on c equals d.Key
select d.Value;

//Get the limited intersections
IEnumerable<string> intersections = results.First();
foreach(var valueSet in results)
{
    intersections = intersections.Intersect(valueSet);
}

var final = from c in categories
join i in intersections on 1 equals 1
select new {Category = c, Intersections = i};

両方のリストに共通する 2 と 3 があると仮定すると、次のようになります。

A   2
A   3
B   2
B   3
于 2013-07-19T03:34:14.733 に答える