如果某个值为 true,我想对列表中的所有项目进行计数,并对 false 值进行计数。
我有这个:
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/