C# 如何通过查询从此Linq组中获取月份名称?
我在LINQ中使用此查询来获取分组数据:C# 如何通过查询从此Linq组中获取月份名称?,c#,linq,C#,Linq,我在LINQ中使用此查询来获取分组数据: string fmt = "yyyyMM"; var pivotedMeanResults = meanDataResults .GroupBy(i => i.Description) .Select(g => new PivotedMeanData { Description = g.Key, Month3Value = g.Where(c => Da
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”转换为“int”
与“System.Globalization.DateTimeFormatInfo.GetContractedMonthName(int)”匹配的最佳重载方法具有一些无效参数
您需要当前月份的名称-1、-2、-3 那你为什么要从你的数据子集中得到月份的名称呢
Month3Name = english.GetAbbreviatedMonthName(currentMonth - 3)
似乎更可能给你一个月的时间
是的,您不能从1月减去2,而期望一个有效的月份:)只需按如下格式设置日期;它将返回日期的月份名称
string month = DateTime.Now.ToString("MMMM", new CultureInfo("en-US"));
//or
month = new DateTime(1, 3, 1).ToString("MMMM", new CultureInfo("en-US"));
一条评论:看起来你在从月份数字中减去1、2和3,以参考之前的月份。请记住,在每年的4月1日之前,这是行不通的。@Tenner:很抱歉,我现在很忙,你能解释一下为什么会这样吗?@A:April=4;三月=3;所以四月-3=1(一月)。但是三月-3=0!(我不确定,这是否与你的特定问题有关。)好吧,我真是太蠢了。我将使用其中一种DateTime方法。