简体   繁体   English

提高生成列表的性能

[英]Improve Performance of Generating List

I have a list that consists of 413 objects. 我有一个由413个对象组成的列表。 Now, I am creating a new list based off of those objects to export to Excel. 现在,我正在创建一个基于这些对象的新列表以导出到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();

When in debug mode, using VS 2017, I am seeing this is taking between 47 and 52 seconds, so, right under a minute to execute. 在调试模式下,使用VS 2017,我看到这需要47到52秒,因此,在一分钟之内执行。

Is there a faster method to use rather than .Select in this scenario? 有没有办法使用,而不是更快的方法.Select在这种情况下?

The problem with the code is more than likely in the 413 calls (one per item in the original list) to the database you are making here: 代码的问题很可能发生在您正在进行的数据库的413次调用(原始列表中每个项目一次)中:

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

Instead of doing this, load all the values at once and consume them from memory: 而不是这样做,一次加载所有值并从内存中消耗它们:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM