我有以下方法进行一些分组
private List<CatalogVehicle> GroupResult(IEnumerable<VehicleAndQuote> vehiclesAndQuotes)
{
var vehicles = vehiclesAndQuotes
.GroupBy(vehicleAndQuote =>
new
{
vehicleAndQuote.Vehicle.VehicleMakeName,
vehicleAndQuote.Vehicle.VehicleModelTypeName,
vehicleAndQuote.Vehicle.VehicleEdition
})
.Select(a => new
{
vehicle = _mapper.Map<VehicleAndQuote, CatalogVehicle>(a.First()),
plans = GetLeasingpPlansGroupedByYearlyMileages(a.ToList()) //<== this one is taking ages
})
.Select(a =>
{
a.vehicle.LeasingPlans = a.plans;
return a.vehicle;
});
return vehicles.ToList();
}
以及在其中调用的方法;
private List<LeasingPlan> GetLeasingpPlansGroupedByYearlyMileages(IEnumerable<VehicleAndQuote> vehicleAndQuotes)
{
return vehicleAndQuotes.GroupBy(quote => quote.Quote.YearlyMileage)
.Select(group => _mapper.Map<List<VehicleAndQuote>, LeasingPlan>(group.ToList()))
.ToList();
}
最后一种方法需要相当长的时间。
IEnumerable<VehicleAndQuote> vehiclesAndQuotes
大约有 30.000 条记录。
是否有任何我没有看到的性能增益?
最佳答案
我正在尝试将您的查询转换为对数据库更友好的版本。
var vehicles = vehiclesAndQuotes
.GroupBy(vehicleAndQuote =>
new {
vehicleAndQuote.Vehicle.VehicleMakeName,
vehicleAndQuote.Vehicle.VehicleModelTypeName,
vehicleAndQuote.Vehicle.VehicleEdition
})
.Select(a => new {
// DB friendly
vehicle = a.First(),
plans = a.GroupBy(quote => quote.Quote.YearlyMileage)
})
.AsEnumerable() // May o may not be needed / passing to LINQ to Objects
.Select(a => {
var vehicle = _mapper.Map<VehicleAndQuote, CatalogVehicle>(a.vehicle);
var plans = a.plans.Select(group => _mapper.Map<IEnumerable<VehicleAndQuote>, LeasingPlan>(group));
vehicle.LeasingPlans = plans;
return vehicle;
});
return vehicles.ToList(); // This should be avoided, specially if you are processing a large collection.
这样你就可以在数据库端进行双重分组。另外,直到最后我才会具体化整个系列。
希望这对您有所帮助!
关于c# - linq 分组结果需要很长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51600850/