我从数据库中以这种形式获取数据:
Item Collection_Period Value
==== ================= =====
Item3 201307 27.2
Item4 201308 19
Item3 201209 2.1
Item2 201307 345
Item1 201309 13.11
Item2 201308 34
Item3 200609 85
Item4 201308 58.2
Item3 201209 2.4
Item2 201309 12.1
Item1 201209 12.3
我需要以这种方式操作数据:
Item CurrMon-3 CurrMon-2 CurrMon-1
===== ========= ========= =========
Item1 13.11
Item2 345 34 12.1
Item3 27.2
Item4 19 58.2
(只需要显示最近三个月的数据)。我正在尝试这个:
public List<PivotedMean> AssociateResultsWithCollectionDate(List<MeanData> meanData)
{
var pivoted = new List<PivotedMean>();
var currentMonth = DateTime.Now.Month;
var results = meanData
.GroupBy(i => i.Description)
.Select(g => new
{
Description = g.Key,
month3 = g.Where(c => c.CollPeriod.Month == currentMonth - 3),
month2 = g.Where(c => c.CollPeriod.Month == currentMonth - 2),
month1 = g.Where(c => c.CollPeriod.Month == currentMonth - 1)
});
return pivoted;
}
我有一个类来保存这些数据:
public class PivotedMean
{
public string Description { get; set; }
public long Month3 { get; set; }
public long Month2 { get; set; }
public long Month1 { get; set; }
}
尽管PivotedMean
该类似乎与 Linq 查询输出一致,但当我替换var results =
为pivoted =
.