LINQ条件和

时间:2013-10-13 08:15:40

标签: c# linq sum where

我有一个模型“水果”存储这样的数据:

date         fruit_code   count
2013/09/30   apple        10
2013/09/30   pear         5
2013/10/01   apple        1
2013/10/01   pear         2
2013/10/02   apple        5

我想要的只是显示每个月的每个水果的总和,输出将是这样的:

date         no_of_apple   no_of_pear
2013/09      10            5
2013/10      6             2

我试图像这样构建linq但是被卡住了:

from o in fruit
let keys = new 
{ 
   date = o.date.ToString("yyyy/MM"),
   fruit = o.fruit_code
}
group o by keys into grp
select new 
{
   date = grp.Key.date,
   no_of_apple = // I got stucked here, wondering how to 
   no_of_pear = // calculate the conditional sum
}

提前谢谢。

5 个答案:

答案 0 :(得分:4)

试试这个:

var result = fruit.GroupBy(i => i.date)
            .Select(i => new
            {
                date = i.Key,
                no_of_apple = i.Where(j => j.fruit_code == "apple").Sum(k => k.count),
                no_of_pear = i.Where(j => j.fruit_code == "pear").Sum(k => k.count)
            });

答案 1 :(得分:0)

假设您有两个来自Apple的{​​{1}}和Pear类,并且它们包含Fruit属性。

Count

答案 2 :(得分:0)

因为您在选择中按日期水果的组合进行分组,所以您只能计算该单一水果的总和:

fruit_count = grp.Sum(o => o.count);

如果您在select子句中另外捕获水果,则最终会将表达式的结果作为{date,fruit,count}的枚举。

这是格式化的更好起点。如果您知道您只有两种类型的水果,您可以按日期分组并依次提取每个水果的列。否则,最初提取水果集允许每个月的内部循环超过水果集(并且记住,根据输入数据,缺少的对象相当于零计数)。

答案 3 :(得分:0)

您仍然可以在.Sum的{​​{1}}内进行比较,然后将Code加在一起

.Count

只有一个问题,你会得到每个月的结果行,一个用于 apple 一个用于 pear ,但也许这不是真正的问题......

:编辑: 我想要真正得到你想要的东西,你必须稍微重组你的团队并在那里做总和

var result = from o in fruit
                group o by
                new
                {
                    date = new DateTime(o.Year, o.Month, 1),
                    Code = o.Code
                }
                into grp
                select new
                {
                    date = grp.Key.date,
                    no_of_apple = grp.Sum(p => p.Code == "apple" ? p.Count : 0), 
                    non_of_pear = grp.Sum(p => p.Code == "pear" ? p.Count : 0)
                };

答案 4 :(得分:0)

您可以按月分组,并在结果选择中计算苹果/梨;

var v = from o in fruit
  group o by new {o.date.Year, o.date.Month} into grp
  select new 
  {
    date = grp.Key,
    no_of_apples = 
      (from a in grp where a.fruit_code == "apple" select a.count).Sum(),
    no_of_pears = 
      (from p in grp where p.fruit_code == "pear" select p.count).Sum(),
  };        
相关问题