c#lambda表达式使用Sum进行多重比较

时间:2012-03-09 16:57:09

标签: c# linq lambda

我正在尝试在lambda表达式中使用Sum方法进行比较,但我想将它用于多重比较。我该如何做到这一点?我看过“Let”和“SelectMany”,但我找不到答案。

下面是代码:

return _dbContext.All<Table>()
            .Where(table => table.CurrentLevel <= salesCriteria.MaxTableLevel)
            .Where(table =>  table.Leg
                            .Where(leg=> salesCriteria.StartDate <= leg.AddDate)
                            .Where(leg=> leg.AddDate <= salesCriteria.EndDate)
                            .Sum(leg => leg.Width) <= salesCriteria.MaxGoalAmount);

正如您所看到的,我正在尝试使用具有某些标准的腿具有某些标准的所有表格,其宽度都加起来小于某个值。我还想确保Sum大于某个最小值。但是,我不能在这里做到这一点.Sum,我失去了名单。那我怎么在这里完成呢?我想要的只是minValue&lt; = .Sum()&lt; = maxValue

2 个答案:

答案 0 :(得分:1)

听起来你想要这样的东西:

return _dbContext.All<Table>()
        .Where(table => table.CurrentLevel <= salesCriteria.MaxTableLevel)
        .Select(table => new { 
           table, 
           legWidth = table.Leg
                           .Where(leg=> salesCriteria.StartDate <= leg.AddDate)
                           .Where(leg=> leg.AddDate <= salesCriteria.EndDate)
                           .Sum(leg => leg.Width)
        })
        .Where(x => x.legWidth <= salesCriteria.MaxGoalAmount &&
                    x.legWidth >= salesCriteria.MinGoalAmount)
        .Select(x => x.table);

所以这里的Select相当于在查询表达式中使用let

作为查询表达式,这将是:

return from table in _dbContext.All<Table>()
       where table.CurrentLevel <= salesCriteria.MaxTableLevel
       let legWidth = table.Leg
                           .Where(leg=> salesCriteria.StartDate <= leg.AddDate)
                           .Where(leg=> leg.AddDate <= salesCriteria.EndDate)
                           .Sum(leg => leg.Width)
       where legWidth <= salesCriteria.MaxGoalAmount &&
             legWidth >= salesCriteria.MinGoalAmount
       select table;

答案 1 :(得分:0)

要获得let的强大功能,您需要从方法链语法切换到查询表达式语法。试试这个:

var goodTables = 
    from table in _dbContext.All<Table>()
    where table.CurrentLevel <= salesCriteria.MaxTableLevel
    let sumOfWidthOfGoodLegs = 
        table.Leg
        .Where(leg=> salesCriteria.StartDate <= leg.AddDate)
        .Where(leg=> leg.AddDate <= salesCriteria.EndDate)
        .Sum(leg => leg.Width)    
    where sumOfWidthOfGoodLegs <= salesCriteria.MaxGoalAmount
    // can insert another where on sumOfWidthOfGoodLegs here as required
    select table;

return goodTables.ToList();

我注意到这是检查只有好的腿的宽度 - 我不相信这是你想要的,但这就是你现在所做的。