gpt4 book ai didi

c# - LINQ 条件求和

转载 作者:太空宇宙 更新时间:2023-11-03 21:40:54 27 4
gpt4 key购买 nike

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

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)
});

关于c# - LINQ 条件求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19343137/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com