c# - 提高生成列表的性能

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

在 Debug模式下,使用 VS 2017,我发现这需要 47 到 52 秒,因此,执行时间不到一分钟。

在这种情况下,是否有比 .Select 更快的方法可以使用?

最佳答案

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

关于c# - 提高生成列表的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51654263/

相关文章:

c# - File.Move() 重命名不起作用

wpf - 慢速组合框性能

sql - Entity Framework select可以阻塞表吗?

c# - SQL Server 全文搜索 - 大型查询

c# - 多线程增量并在没有锁的情况下跳过0?

c# - 如何修复 System.Drawing.dll 中的控制台应用程序异常 "' System.ArgumentException'

javascript - 如何在 Angular 中使用 Promise 并摆脱超时

android - Android 中的电源配置文件

c - 为什么执行时间会根据数据类型而变化?

linq - 如何使用 EF Code First 表示期权计算列?