English 中文(简体)
上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();

I now need to get the average of last N months where N is input in a textbox by the user. Please advise how to get avg of last N from an ordered collection using Linq. thank you

最佳回答

如果您知道收藏中的项目数量( 或者使用 Count () ) ), 您可以跳过第一个 Count - N 项 :

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

我创建了一种扩展方法, 使用不要求调用 .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;
}

要使用它, 如果您的列表被命名为 < code> sequence , 请调用 < code> sequence. take Last(n) 获取最后的 < code>n 记录 。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签