c# - 如何在 LINQ 中执行嵌套的加入、添加和分组?

标签 c# linq

我有两个对象,我们称它们为 InputOutput

Input 具有属性 Input_IDLabelInput_Amt
Output 具有属性 Output_IDOutput_Amt

我想在 LINQ 中执行等效的 SQL 语句:

SELECT Label, Sum(Added_Amount) as Amount FROM
    (SELECT I.Label, I.Input_Amt + ISNULL(O.Output_Amt, 0) as Added_Amount
    FROM Input I LEFT OUTER JOIN Output O ON I.Input_ID = O.Output_ID)
GROUP BY Label

对于内部查询,我写的是这样的:

var InnerQuery = from i in input
                 join o in output
                 on i.Input_ID equals o.Output_ID into joined
                 from leftjoin in joined.DefaultIfEmpty()
                 select new
                 {
                     Label = i.Label,
                     AddedAmount = (i.Input_Amt + leftjoin.Output_Amt)
                 };

然而,在测试中,该语句返回 null。是什么赋予了?

此外,在将我的金额相加后,如何在单个 LINQ 语句中继续所需的查询并执行分组?

最佳答案

好的,现在我对发生的事情有了更好的了解,主要问题是您没有得到与 ISNULL 位等效的信息。试试这个:

var InnerQuery = from i in input
                 join o in output
                 on i.Input_ID equals o.Output_ID into joined
                 from leftjoin in joined.DefaultIfEmpty()
                 select new
                 {
                     Label = i.Label,
                     AddedAmount = (i.Input_Amt + (leftjoin == null ? 0 : leftjoin.Output_Amt))
                 };

关于c# - 如何在 LINQ 中执行嵌套的加入、添加和分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/254784/

相关文章:

c# - c# 编译器是否在编译期间解析引用的引用?

c# - 搜索所有单词的 StartsWith 扩展

c# - 如何捕获多个 key ?

c# - 3 个数组到 1 个 IEnumerable<test>

linq - 将 XML 文档转换为字符串数组时出现问题

c# - 如何正确检查 IEnumerable 的现有结果

c# - 在不使用 foreach 循环的 C# 中填充列表中的列表。更好的方法?

c# - c#中的动态控制

c# - 对 asp.net mvc 中的身份验证非常困惑

c# - 解析 CSV 文件