繁体   English   中英

LINQ最近N个平均值

[英]linq average of last N

被看起来简单的问题困扰。 我有

var SummaryCollection = (from n in ...long criteria with group by clause) 
into g select new 
{     MonthYear = g.Key, 
      Amount = g.Sum(p=>p.Amount)}).OrderBy(p=>p.MonthYear);
}

我现在得到的数据看起来像这样

Jan2009 $100
Feb2009 $134
... and so on

最后我有

  decimal avgAmount = (from x in SummaryCollection select x.Amount).Average();

现在,我需要获取用户在文本框中输入N的最近N个月的平均值。 请告知如何使用Linq从有序集合中获取最后N个平均值。 谢谢

如果您知道集合中的项目数(或使用Count() ),则可以跳过第一个Count - N项目:

 decimal avgAmount = SummaryCollection.Skip(SummaryCollection.Count() - N)
                                      .Select(x => x.Amount)
                                      .Average();

我创建了一个扩展方法,该方法使用的Queue<T>不需要在序列上调用.Count或重复多次。

public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> @this, int n) {
    var queue = new Queue<T>(n + 1);

    foreach (var element in @this) {
        queue.Enqueue(element);

        if(queue.Count > n) queue.Dequeue();
    }

    return queue;
}

要使用它,如果您的列表名为sequence ,则只需调用sequence.TakeLast(n)即可获取最后的n条记录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM