1

我从数据库中以这种形式获取数据:

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 =.

4

1 回答 1

5

那是因为pivoted是 PivotedMean 的列表,并且 LINQ 查询(在您的情况下)返回IEnumerable匿名类的一个。

  • 您可以.ToList()在 LINQ 查询的末尾添加,以便将其评估为列表。
  • 您可以将其映射到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

}

或者,尽可能使用IEnumerables 而不是Lists。它们提供了对“经历事物”的抽象。

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

于 2013-10-17T07:15:57.047 回答