【问题标题】:Linq query with a Conditional WHERE Clause带有条件 WHERE 子句的 Linq 查询
【发布时间】:2010-05-17 14:49:31
【问题描述】:

我是 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 语句之外不可用

如果有任何帮助,将不胜感激

问候

幽灵

【问题讨论】:

    标签: c# linq


    【解决方案1】:
    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; 
    

    【讨论】:

    • 我认为你的条件与问题相反:)
    • @jball:也许是故意的,给那些在阅读和理解代码之前复制和粘贴代码的人上一课?
    • 我在使用 LINQ 进行动态分组时遇到了类似的问题。你能看看here吗?
    【解决方案2】:

    尝试一下(我的 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 
             };
    

    【讨论】:

    • where b.BranchKeySelected.Contains("")?这不是笔误吗?它将在所有字符串上返回truenull 除外)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2016-02-05
    • 1970-01-01
    相关资源
    最近更新 更多