我的代码类似于:
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中执行此操作?
感谢。
答案 0 :(得分: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
。
答案 1 :(得分: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