i.ItemID, i => new { isScheduled = -6ren">
gpt4 book ai didi

c# - LINQ 分组依据和 "count-if"

转载 作者:行者123 更新时间:2023-11-30 22:14:20 24 4
gpt4 key购买 nike

如果值为真,我想对列表中的所有项目进行计数,对假值进行计数。

我有这个:

Items.GroupBy(
i => i.ItemID,
i => new { isScheduled = i.isScheduled },
(key, g) => new ItemStatistics()
{
ItemID = key,
ScheduledItems = g.Count(g=>g.isScheduled),
UnscheduledItems = g.Count(g=> !g.isScheduled)
}).ToList();

这给了我以下编译错误:

Cannot convert lambda expression to type 'System.Collections.Generic.IEqualityComparer' because it is not a delegate type

就好像它期待一个不同的方法重载

当我这样做时,一切似乎都很好......

Items.GroupBy(
i => i.ItemID,
i => new { isScheduled = i.isScheduled },
(key, g) => new ItemStatistics()
{
ItemID = key,
ScheduledItems = g.Count(),
UnscheduledItems = g.Count()
}).ToList();

为什么当我从接受它的计数方法中删除 g=> !g.isScheduled 表达式时?

最佳答案

找到了……啊!

当我可以使用“g”作为组内内部 lambda 表达式的变量时,因为它指的是原始组“g”。所以我将 g=>g.isScheduled 更改为 i=>i.isScheduled

Items.GroupBy(
i => i.ItemID,
i => new { isScheduled = i.isScheduled },
(key, g) => new ItemStatistics()
{
ItemID = key,
ScheduledItems = g.Count(i=>i.isScheduled),
UnscheduledItems = g.Count(i=> !i.isScheduled)
}).ToList();

现在一切正常

关于c# - LINQ 分组依据和 "count-if",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18555860/

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