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 回答