我使用LINQ这个查询获取分组数据:如何通过查询从此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>
'到‘廉政’的最佳重载方法匹配‘System.Globalization.DateTimeFormatInfo.GetAbbreviatedMonthName(INT)’有一些无效参数
一个评论:它看起来像是从月份数中减去一,二和三以便引用前几个月。请记住,这不会在每年的4月1日之前运行。 – Tenner
@Tenner:对不起,我现在很密集,你能解释一下为什么这样吗? – Animesh
@A:April = 4;三月= 3;所以4月 - 3 = 1(1月)。但3月 - 3 = 0! (我不确定,如果这是你的特定查询的关注点。) – elgonzo