提高生成列表的性能

时间:2018-08-02 12:56:42

标签: c# performance entity-framework linq

我有一个包含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();

在调试模式下,使用VS 2017,我看到这需要47到52秒,因此,不到一分钟的时间即可执行。

在这种情况下,有没有比.Select更快的使用方法?

1 个答案:

答案 0 :(得分:10)

在您在此处进行的数据库的413次调用(原始列表中的每个项目一个)中,代码问题的可能性更大:

PropertyTwo = db.MyTable.Find(x.NavProperty.subcategoryID).Text

代替执行此操作,而是一次加载所有值并从内存中使用它们:

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();