【发布时间】: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 方法。