【问题标题】:How do I get month names from this Linq group by query?如何通过查询从此 Linq 组中获取月份名称?
【发布时间】:2013-10-21 20:53:36
【问题描述】:

我在 LINQ 中使用此查询来获取分组数据:

string fmt = "yyyyMM";
var pivotedMeanResults =
    meanDataResults
    .GroupBy(i => i.Description)
    .Select(g => new PivotedMeanData
    {
        Description = g.Key,
        Month3Value = g.Where(c => DateTime.ParseExact(c.CollectionPeriod, fmt, invariantCulture).Month == currentMonth - 3).FirstOrDefault().LabResultNo.ToString(),
        Month2Value = g.Where(c => DateTime.ParseExact(c.CollectionPeriod, fmt, invariantCulture).Month == currentMonth - 2).FirstOrDefault().LabResultNo.ToString(),
        Month1Value = g.Where(c => DateTime.ParseExact(c.CollectionPeriod, fmt, invariantCulture).Month == currentMonth - 1).FirstOrDefault().LabResultNo.ToString()
        Month3Name = ? //
        Month2Name = ? //
        Month1Name = ? //
    }).ToList();

数据格式如下:

Item    Collection_Period   Value
====    =================   =====
Item4       201308          19
Item3       201209          2.1
Item2       201307          345
Item1       201309          13.11
Item2       201308          34
Item4       201308          58.2
Item3       201209          2.4
Item2       201309          12.1
Item1       201209          12.3

我需要将数据处理成这种格式,我根据需要得到:

Item    Month3Name  Month2Name  Month1Name
=====   =========   =========   =========
Item1                           13.11
Item2   345         34          12.1
Item3   
Item4   19          58.2

但我想知道是否可以根据分组中等效月份值的派生方式来获取月份名称(Month1Name、Month2Name、Month3Name)?


PS:我知道我可以生成月份名称可以这样生成:

CultureInfo cInfo = new CultureInfo("en-US");
DateTimeFormatInfo english = cInfo.DateTimeFormat;
english.GetAbbreviatedMonthName(integer)

所以我尝试了这个

Month3Name = english.GetAbbreviatedMonthName
(g.Where(DateTime.ParseExact(c.CollectionPeriod, fmt, invariantCulture)
.Month == currentMonth - 3))

但我得到了错误:

参数 1:无法从 'System.Collections.Generic.IEnumerable<Namespace.Type.MeanData>' 转换为 'int'

'System.Globalization.DateTimeFormatInfo.GetAbbreviatedMonthName(int)' 的最佳重载方法匹配有一些无效参数

【问题讨论】:

  • 一条评论:看起来您正在从月份数字中减去一、二和三,以便参考前几个月。请记住,这在每年的 4 月 1 日之前不起作用。
  • @Tenner:对不起,我现在这么密集,你能解释一下为什么会这样吗?
  • @A: April=4;三月=3;所以四月 - 3 = 1(一月)。但是三月 - 3 = 0! (我不确定,这是否与您的特定查询有关。)
  • 好吧,这真是太愚蠢了。为此,我将使用其中一种 DateTime 方法。

标签: c# linq


【解决方案1】:

您想要当前月份的名称 -1、-2、-3。

那你为什么要从你的数据子集中获取月份的名称??

Month3Name = english.GetAbbreviatedMonthName(currentMonth - 3)

似乎更有可能给你一个月份名称?

是的,你不能从一月减去 2 并期望一个有效的月份:)

【讨论】:

    【解决方案2】:

    只需像下面这样格式化日期;它将返回日期的月份名称。

            string month = DateTime.Now.ToString("MMMM", new CultureInfo("en-US"));
            //or
            month = new DateTime(1, 3, 1).ToString("MMMM", new CultureInfo("en-US"));
    

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      • 2015-11-29
      • 1970-01-01
      • 2018-03-01
      • 2022-08-17
      相关资源
      最近更新 更多