c# - Linq 合并查询

标签 c# linq

我有两个查询想要合并。这可能是左外连接,但看起来有所不同。

第一个查询从表中选择不同的内容:

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/

相关文章:

c# - 使用 SharpSVN 添加文件

c# - 运行时尝试查找 exe/dll 而不是 .winmd 引用

c# - LINQ 聚合与子聚合

c# - 包含 namespace 的 XDocument

javascript - 使用 C# 检查来确定 JQuery 参数的值

c# - (NetNative)NetworkInterface.GetNetworkInterfaces() 中的 NotImplementedException Win IoT Core 14393

c# - 如何在 linq 中组合两个字段?

c# - 值 '\r\n' 的格式无效 .","ExceptionType":"System. FormatException

c# - LINQ:模拟 sql 的 EXISTS?

c# - 错误 : "The specified LINQ expression contains references to queries that are associated with different contexts"