linq左边连接where where子句显示所有左表无论如何

时间:2014-07-08 11:27:04

标签: c# linq

我正在与一些linq挣扎

我想要CustomerDiscountGroups表中的所有内容,然后从另一个表中加入一列。如果where条件显示的是没有CustomerDiscounts我仍然希望它显示来自CustomerDiscountGroups表的所有列,并且状态0表示Discount_PC(小数)

继承人我的尝试

from c in CustomerDiscountGroups
join d in CustomerDiscounts on c.ID equals d.Discount_ID into cd
    from cdi in (from f in cd
    where f.AccountNo ==  "test" 
    select f).DefaultIfEmpty()
select new
{
    c.ID,
    c.DisplayName,
    c.Image,
    c.Added,
    c.Added_by,
    c.Edited,
    c.Edited_by,
    //cdi.Discount_PC
}

1 个答案:

答案 0 :(得分:2)

DefaultIfEmptycdi null,即使它属于CustomerDiscounts类型。您必须在select子句中处理这种情况:

select new
{
    c.ID,
    c.DisplayName,
    c.Image,
    c.Added,
    c.Added_by,
    c.Edited,
    c.Edited_by,
    Discount_PC = cdi == null ? 0 : cdi.Discount_PC
}

为此编写一个三元运算符有点尴尬,事实上,在C#6中可能会有一个新的短手操作符。