LINQ 条件总和
本文关键字:条件 LINQ | 更新日期: 2023-09-27 18:35:18
我有一个模型"水果"存储这样的数据:
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
}
提前谢谢你。
试试这个:
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)
});
假设你有两个类Apple
和Pear
派生自Fruit
,并且它们包含一个Count
属性。
from o in fruit
let month = o.date.ToString("yyyy/MM")
group o by month into grp
select new
{
date = grp.Key,
no_of_apple = grp.OfType<Apple>.Sum(apple=>apple.Count),
no_of_pear = grp.OfType<Pear>.Sum(pear=>pear.Count),
}
因为您在选择中按日期和水果的组合分组,所以您只能计算该单个水果的总和:
fruit_count = grp.Sum(o => o.count);
如果在 select 子句中另外捕获水果,则表达式的结果最终为 while 是 { date, fruit, count } 的枚举。
然后,这是格式化的更好起点。如果您知道您只有两种类型的水果,您可以按日期分组并依次提取每种水果作为列。否则,最初提取水果集允许每个月对水果集进行内部循环(请记住,根据输入数据,缺少的对象相当于零计数)。
您仍然可以在.Sum
内对Code
进行比较,然后将.Count
相加
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)
};
只有一个问题,你每个月都会得到结果行,一个是苹果,一个是梨,但也许这不是真正的问题......
:编辑:我认为要真正得到你想要的东西,你必须稍微重组你的团队并在那里做总和。
var result = from o in fruit
group o by
new
{
date = new DateTime(o.Year, o.Month, 1),
Code = o.Code,
no_of_apple = fruit
.Where(f => f.Month == o.Month && f.Year == o.Year)
.Sum(p => p.Code == "apple" ? p.Count : 0),
no_of_pear = fruit
.Where(f => f.Month == o.Month && f.Year == o.Year)
.Sum(p => p.Code == "pear" ? p.Count : 0)
}
into grp
select new
{
date = grp.Key.date,
no_of_apple = grp.Key.no_of_apple,
no_of_pear = grp.Key.no_of_pear
};
您可以按月分组并计算结果选择中的苹果/梨;
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(),
};