联盟的两个结果

时间:2015-02-02 20:06:36

标签: c# linq

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

我需要将cd的结果合并为34

我可以在LINQ查询中将这两个结果联合起来吗?

2 个答案:

答案 0 :(得分:3)

使用Enumerable.Union

var combined = c.Union(d);

如果您只对Union感兴趣,那么您可以删除ToList cd的电话,例如(请参阅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}}使用延迟执行。