我使用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