带有条件WHERE子句的Linq查询

时间:2010-05-17 14:49:31

标签: c# linq

我是LINQ的新手,所以请事先道歉

我有以下Linq查询: -

var OrdersByBranches =
    from a in AllOrders
    join b in AllBranchKeys
        on a.BranchKey equals b.BranchKey
    orderby a.Date
    group a by new { a.Date, a.paymentMethod } into BranchOrderGrouped
    select new
    {
        BranchOrderGrouped.Key.Date,
        CurrencyAmount = BranchOrderGrouped.Sum(a =>
        a.CurrencyAmount),
        BranchOrderGrouped.Key.paymentMethod
    };

我需要在上面的查询中包含一个where子句...仅当一个变量被调用时 BranchKeySelected是“”

我尝试过使用If Else语句并将上述相同的查询重复使用 一个包含where子句和一个NOT。 ......但是当我这样做时......然后是OrdersByBranches 在IF声明之外不可用

非常感谢任何帮助

此致

2 个答案:

答案 0 :(得分:7)

var OrdersByBranches = 
    from a in AllOrders 
    join b in AllBranchKeys on a.BranchKey equals b.BranchKey 
    orderby a.Date 
    group a by new { a.Date, a.paymentMethod } into BranchOrderGrouped 
    select new { 
        BranchOrderGrouped.Key.Date, 
        CurrencyAmount = BranchOrderGrouped.Sum(a =>  a.CurrencyAmount), 
        BranchOrderGrouped.Key.paymentMethod 
    };

if(string.IsNullOrEmpty(BranchKeySelected ))
{
    OrdersByBranches = OrdersByBranches.Where(/*blbabla*/);
}

return OrdersByBranches; 

答案 1 :(得分:1)

尝试(我的linq没有打磨)

var OrdersByBranches = from a in AllOrders 
    join b in AllBranchKeys on a.BranchKey equals b.BranchKey 
    where b.BranchKeySelected.Contains("")
    orderby a.Date group a by new 
        {
            a.Date, 
            a.paymentMethod
        }
        into BranchOrderGrouped
    select new
        {
            BranchOrderGrouped.Key.Date, 
            CurrencyAmount = BranchOrderGrouped.Sum(a =>  a.CurrencyAmount),
            BranchOrderGrouped.Key.paymentMethod 
         };