Gri*_*zly 2 c# linq performance entity-framework
我有一个由413个对象组成的列表.现在,我正在创建一个基于这些对象的新列表以导出到Excel.
lstDailySummary = (List<DailySummary>)Session["Paging"];
List<ExportExcel> lstExportedExcel = lstDailySummary
.Select(x => new ExportExcel
{
PropertyOne = x.ACInfo.RegNumber,
PropertyTwo = db.MyTable.Find(x.NavProperty.subcategoryID).Text,
PropertyThree = x.NavProperty.text,
PropertyFour = (!string.IsNullOrWhiteSpace(x.Agcy.ToString())) ? x.codeAgcy.location : " ",
PropertyFive = x.EventLocation,
PropertySix = x.codeCounty.county,
PropSeven = x.Flight,
PropEight = x.FlightDay.ToString("MM/dd/yyyy HH:mm"),
PropNine = x.IncidentNumber,
PropTen = x.codeLocation.Location,
PropEleven = x.Summary,
PropTwelve = x.Total,
PropThirteen = x.ATime
})
.ToList();
Run Code Online (Sandbox Code Playgroud)
在调试模式下,使用VS 2017,我看到这需要47到52秒,因此,在一分钟之内执行.
是否有更快的方法来使用而不是.Select在这种情况下?
SO *_*ood 10
代码的问题很可能发生在您正在进行的数据库的413次调用(原始列表中每个项目一次)中:
PropertyTwo = db.MyTable.Find(x.NavProperty.subcategoryID).Text
Run Code Online (Sandbox Code Playgroud)
而不是这样做,一次加载所有值并从内存中消耗它们:
var distinctSubcategoryIds = lstDailySummary
.Select(x => x.NavProperty.subcategoryID)
.Distinct();
var dataForPropertyTwo = db.MyTable
.Where(x => distinctSubcategoryIds.Contains(x.Id))
.ToDictionary(x => x.Id, x => x.Text);
List<ExportExcel> lstExportedExcel = lstDailySummary.Select(x => new ExportExcel
{
PropertyOne = x.ACInfo.RegNumber,
PropertyTwo = dataForPropertyTwo[x.NavProperty.subcategoryID],
PropertyThree = x.NavProperty.text,
PropertyFour = (!string.IsNullOrWhiteSpace(x.Agcy.ToString())) ? x.codeAgcy.location : " ",
PropertyFive = x.EventLocation,
PropertySix = x.codeCounty.county,
PropSeven = x.Flight,
PropEight = x.FlightDay.ToString("MM/dd/yyyy HH:mm"),
PropNine = x.IncidentNumber,
PropTen = x.codeLocation.Location,
PropEleven = x.Summary,
PropTwelve = x.Total,
PropThirteen = x.ATime
}).ToList();
Run Code Online (Sandbox Code Playgroud)