Dictionary<int, int> first = new Dictionary<int, int>();
first.Add(1, 5);
first.Add(2, 4);
first.Add(3, 7);
Dictionary<int, int> second = new Dictionary<int, int>();
second .Add(2, 1);
second .Add(3, 2);
second .Add(4, 3);
var c = first.Where(x => x.Value > 5).Select(x => x.Key).ToList(); // this gives me 3
var d = second.Where(x => x.Value >= 2).Select(x => x.Key).ToList(); // this give me 3 and 4
我需要将c
和d
的结果合并为3
和4
。
我可以在LINQ查询中将这两个结果联合起来吗?
答案 0 :(得分:3)
var combined = c.Union(d);
如果您只对Union
感兴趣,那么您可以删除ToList
c
和d
的电话,例如(请参阅why ):
var c = first.Where(x => x.Value > 5).Select(x => x.Key); // this gives me 3
var d = second.Where(x => x.Value >= 2).Select(x => x.Key); // this give me 3 and 4
var combined = c.Union(d).ToList();
答案 1 :(得分:3)
您将使用Enumerable的Union
方法,如下所示:
var union = c.Union(d);
Union
var union = first.Where(x => x.Value > 5)
.Select(x => x.Key)
.Union(second.Where(y => y.Value >= 2)
.Select(y => y.Key))
.ToList();
上的MSDN {/ 3}}。
或者,如果这样做是一次性查询:
Union
这实际上可能更优选,因为{{1}}使用延迟执行。