我有两个查询想要合并。这可能是左外连接,但看起来有所不同。
第一个查询从表中选择不同的内容:
var d = from d in db.Data
select (d.ID, d.Label, Value = 0).Distinct;
假设这会返回以下内容:
{1,"Apple",0}
{2,"Banana",0}
{3,"Cabbage",0}
然后我有另一个查询进行不同的选择:
var s = from d in db.Data
where d.Label != "Apple"
select (d.ID, d.Label, d.Value);
这将返回:
{2,"Banana",34}
{3,"Cabbage",17}
然后我想要第三个查询,根据 d 和 s 的 ID 和标签将它们连接在一起。我希望结果如下所示:
{1,"Apple",0}
{2,"Banana",34}
{3,"Cabbage",17}
我基本上只是更新第三个查询中的数字,但我不知道应该如何执行此操作。感觉它应该是一个简单的连接,但我就是无法让它工作。
最佳答案
这应该有效:
var query1 = from d in db.Data
select new { d.ID, d.Label, Value = 0 }.Distinct();
var query2 = from d in db.Data
where d.Label != "Apple"
select new { d.ID, d.Label, d.Value };
var result =
from d1 in query1
join d2 in query2 on new { d1.ID, d1.Label } equals new { d2.ID, d2.Label } into j
from d2 in j.DefaultIfEmpty()
select new
{
d1.ID,
d1.Label,
Value = d2 != null ? d2.Value : d1.Value
};
注意:您确定要加入 ID 和标签吗?这对我来说似乎很奇怪......标签不应该是 key 的一部分,因此对于给定的 ID 来说它应该始终相同
关于c# - Linq 合并查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3819868/