如何使用聚合重写几个独立的LINQ查询到单一()? [英] How to rewrite several independent LINQ queries into single one using Aggregate()?

查看:107
本文介绍了如何使用聚合重写几个独立的LINQ查询到单一()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的下一个极不优化code:

I have next very non-optimized code:

void Summarize(IEnumerable<Section> sections)
{
    this.DateBegin = sections.Select(s => s.Date).Min();
    this.DateEnd = sections.Select(s => s.Date).Max();
    this.Income = sections.Where(s => s.IsIncome).Sum(r => r.Amount);
    this.ExpenditureBank = sections.Where(s => s.IsExpenditureBank).Sum(r => r.Amount);
    this.ExpenditureClient = sections.Where(s => s.IsExpenditureClient).Sum(r => r.Amount);
    this.Expenditure = this.ExpenditureBank + this.ExpenditureClient;
}

如何重写如此,它使用 IEnumerable.Aggregate(),如果适用?

推荐答案

有时候,一个良好的老式的foreach 循环是适合这份工作的最佳工具。我认为这是这里的情况,否则你要么将要列举的部分多次还是有一些非常不可读LINQ code。

Sometimes a good old fashioned foreach loop is the best tool for the job. I think that's the case here otherwise you're either going to be enumerating the sections multiple times or have some very unreadable LINQ code.

虽然你可能提前知道时间的部分参数将是一个数组或集合或什么不是,它可能是,这是非常昂贵的枚举或东西,不产生枚举之间是一致的价值观。 IEnumerable的,有时会让你大吃一惊。

And although you probably know ahead of time that the sections parameter will be an array or collection or what not, it might be something that is very expensive to enumerate or something that doesn't yield consistent values between enumerations. IEnumerable can surprise you sometimes.

这篇关于如何使用聚合重写几个独立的LINQ查询到单一()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆