使用LINQ旋转数据

时间:2013-10-17 07:11:53

标签: c# linq

我从数据库中获取此表单中的数据:

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 =时出现错误。

1 个答案:

答案 0 :(得分:5)

这是因为pivoted是PivotedMean的列表,LINQ查询(在您的情况下)返回匿名类的IEnumerable

  • 您可以在LINQ查询的末尾添加.ToList(),以便将其评估为列表。
  • 您可以将其映射到PivotedMean实例而不是匿名对象。

例如:

public List<PivotedMean> AssociateResultsWithCollectionDate(List<MeanData> meanData)
{

    var currentMonth = DateTime.Now.Month;
    return meanData
        .GroupBy(i => i.Description)
        .Select(g => new PivotedMean // notice the class name here
        { // this is now a PivotedMean initializer
            Description = g.Key, // You were also missing some caps here
            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)
        }).ToList(); // notice the ToList

}

或者,尽可能使用IEnumerable而不是List。它们提供了“通过事物”的抽象。

编码时,对接口而不是实现进行编码被认为是最佳做法,因为您只需担心并依赖于元素的行为而不是实际类型。

相关问题