【问题标题】:LINQ Group by and "count-if"LINQ Group by 和“count-if”
【发布时间】:2013-09-01 06:28:31
【问题描述】:

如果值为真,我想计算列表中的所有项目,并计算假值。

我有这个:

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

这给了我以下编译错误:

无法将 lambda 表达式转换为类型 'System.Collections.Generic.IEqualityComparer' 因为它不是 委托类型

好像它期望不同的方法重载

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

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 表达式时?

【问题讨论】:

  • 您在ScheduledItems = g.Count()UnscheduledItems = g.Count() 之间漏掉了一些,
  • @KingKing nope...它在代码中带有逗号..我只是复制错了..(编辑了问题代码...)

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


【解决方案1】:

找到了……啊!

当我可以使用“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();

现在一切正常

【讨论】:

  • 为什么不直接选择i=>i.isScheduled?那么你只需要g.Count(i=>i)g.Count(i=>!i)
  • @KingKing 我发现i=>i.isScheduledi=>i 更具可读性
  • 如果您想要可读性,您也可以将其命名为g.Count(isScheduled=>isScheduled)g.Count(isScheduled=>!isScheduled)。我猜new {...} 类型会比bool 更大。
  • 真的......谢谢......它的这一个字母 lambdas 卡在我的脑海里 :)
猜你喜欢
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多