代码之家  ›  专栏  ›  技术社区  ›  Grizzly

提高生成列表的性能

  •  2
  • Grizzly  · 技术社区  · 7 年前

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

    在调试模式下,使用VS2017,我看到这需要47到52秒,所以,在一分钟内执行。

    有没有比 .Select 在这种情况下?

    1 回复  |  直到 7 年前
        1
  •  10
  •   Camilo Terevinto Chase R Lewis    7 年前

    代码的问题很可能出现在对数据库的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();