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

标签 c# asp.net-mvc linq grouping linq-to-objects

如果某个值为 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/

相关文章:

.net - 具有扎实的 WPF/.NET 背景学习 ASP.NET MVC

c# - 如何使用 LINQ 执行单词搜索?

c# - 将 SQL 语句转换为具有 2 列的 Linq-to-SQL,其中 count(*) 不起作用

c# - 如何执行递归搜索?

c# - ASP.NET MVC 5 模型绑定(bind)不起作用

c# - 尚未注册该类型的服务

c# - CheckedListBox Action ItemCheck 删除项目?

C# - DataGridView 和 SelectedCells - 查找选定单元格的行索引

asp.net - IgnoreRoute with webservice - 从路由中排除 asmx URL

c# - 从 VBA 转换为 C#