Tag: aggregate

如何使用Aggregate()将几个独立的LINQ查询重写为单个查询?

我有下一个非优化的代码: void Summarize(IEnumerable 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()重写它?

LINQ中的聚合与总和性能

下面给出了三种不同的实现,即查找IEnumerable 源的总和,以及源具有10,000个整数所花费的时间。 source.Aggregate(0, (result, element) => result + element); 需要3毫秒 source.Sum(c => c); 需要12毫秒 source.Sum(); 需要1毫秒 我想知道为什么第二次实施比第一次实施贵四倍。 不应该与第三个实现相同。

德米特法则混淆

我希望有人可以帮我解释一下demeter法则。 如果我有一个我假设的类是聚合根,并且其中有一个子类集合,那么通过聚合根访问它们来更新这些子类的属性是不合法的吗? 例如 public class Company { // company has a number of employees public List Employees {get; set;} } public class Employee { // each employee has a lastname public int Id {get; set;} public string LastName {get; set;} // other properties of employee } 假设我有一个正在访问公司类的客户端,如果它违反了得墨忒耳的法则,就像是。 Employee e = aCompany.Employees.Where(e => e.Id == 1).Single(); […]

C#LINQ – 如何动态构建Group By子句

我正在处理应用程序,用户可以在其中选择他/她想要在屏幕上看到的列以及要分组或聚合的列。 因此,在我的LINQ部分中,我实际上应该将包含列名的变量传递给group by和aggregate子句。 请记住, DataTable dt每次都可能包含不同的数据(例如员工信息,采购订单,性能统计等)。 我只能通过dt.Columns[i].ColumnName和dt.Columns[i].DataType.Name在运行时获取有关数据的信息。 任何人都可以建议如何做到这一点,我需要的是这样的事情: SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); var query = from row in dt.AsEnumerable() group row by new { foreach(DataColumn column in dt.Columns) { row[column.ColumnName]; } } into grp select new { foreach(DataColumn column in dt.Columns) { if(column.DataType.Name == “Decimal”) { Sum(grp[column.ColumnName]); }else{ […]