两个结果的联合
Union of two results
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 查询中合并这两个结果吗?
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();
您将使用 Enumerable 的 Union
方法,如下所示:
var union = c.Union(d);
可以在 Union
上找到 MSDN here。
或者,如果将此作为一次性查询执行:
var union = first.Where(x => x.Value > 5)
.Select(x => x.Key)
.Union(second.Where(y => y.Value >= 2)
.Select(y => y.Key))
.ToList();
这实际上也可能更可取,因为 Union
采用延迟执行。
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 查询中合并这两个结果吗?
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();
您将使用 Enumerable 的 Union
方法,如下所示:
var union = c.Union(d);
可以在 Union
上找到 MSDN here。
或者,如果将此作为一次性查询执行:
var union = first.Where(x => x.Value > 5)
.Select(x => x.Key)
.Union(second.Where(y => y.Value >= 2)
.Select(y => y.Key))
.ToList();
这实际上也可能更可取,因为 Union
采用延迟执行。