【问题标题】:.SelectMany with C#.SelectMany 与 C#
【发布时间】:2017-03-30 21:49:49
【问题描述】:

我找到了这篇文章,我需要类似的东西

stackoverflow.com/questions/41282053/groupby-multiple-date-properties-by-month-and-year-in-linq/43112774#43112774

我需要按月和年分组,但同时我需要一个主元素的属性,我无法访问

var departments = stops 
    .SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year }
    .Where(dt => dt != null).Select(dt => x.InitDate))
    .GroupBy(dt => new { dt.Month, dt.Year }) 
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year) 
    .Select(g => new 
    { 
        Key = g.Key.Month, 
        Año = g.Key.Year, 
        Duration = 0, 
        Count = g.Count() 
    });

我需要访问“stops.Duration”,但如果我这样做:.SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year, x.Duration }

它没有按月-年对我进行分组

谁能帮帮我?

对不起我的英语,非常感谢你

【问题讨论】:

  • 持续时间需要做什么?平均/最大/最小/总和/计数?
  • 我需要对持续时间进行求和
  • 离题评论,永远不要在代码中使用特殊字符。我在看名字 Año(西班牙语中的年份)。帮自己一个忙,避免这样做。

标签: c# linq


【解决方案1】:

这段代码应该这样做:

var departments = stops 
    .Where(stop => stop.InitDate != null)
    .SelectMany(stop => new[] { Month = stop.InitDate.Month, Year = stop.InitDate.Year, Duration = stop.Duration })
    .GroupBy(dt => new { dt.Month, dt.Year }) 
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year) 
    .Select(g => new 
    { 
        Key = g.Key.Month, 
        Año = g.Key.Year, 
        Duration = g.Sum(v => v.Duration), 
        Count = g.Count() 
    });

它选择持续时间,按月和年分组,并使用分组结果中的持续时间总和。

【讨论】:

  • 您应该解释问题出在哪里 - Where 被应用于SelectMany参数,而不是停止,返回意外结果
  • 我有一个问题,因为当我执行 Año = g.Sum(v => v.Duration) 时,无法识别持续时间。我也认为你需要一个括号“)”
  • 还有一个问题。 G 是日期时间,不是停止类型。
  • 没有。它是一种匿名类型。
  • 如果我使用此代码,第一个问题是在 .SelectMany(x => new[] { Month = stop.InitDate.Month 中使用时,当前上下文中不存在“stop” , Year = stop.InitDate.Year, Duration = stop.Duration }. 不知道是什么问题
【解决方案2】:
int Month = 0, Year= 0, Duration = 0;
var departments = stops 
    .Where(stop => stop.InitDate != null)
    .SelectMany(stop => new[] { Month = stop.InitDate.Month, Year = stop.InitDate.Year, Duration = stop.Duration })
    .GroupBy(dt => new { Month, Year }) 
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year) 
    .Select(g => new 
    { 
        Key = g.Key.Month, 
        Año = g.Key.Year, 
        Duration = g.Sum(v => Duration), 
        Count = g.Count() 
    });

对我来说,这是最终的解决方案

【讨论】:

  • 该代码不会对任何内容进行分组,因为它会根据常量进行分组。
  • 问题出在 GroupBy 上?如果我写“new { dt.Month, dt.Year }”,编译器会指示找不到整数月份(stop.InitDate.Month 是整数)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
  • 2019-04-15
  • 1970-01-01
相关资源
最近更新 更多