c# - 提高生成列表的性能
问题描述
我有一个包含 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
在这种情况下更快的方法来使用?
解决方案
代码问题很可能出现在对您在此处进行的数据库的 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();
推荐阅读
- php - 如何防止表格出现
- keycloak - 如何在 keycloak 4.6 中排除 url?
- cassandra - Cassandra 数据分布
- javascript - 为什么 if/then 对 document.querySelector 不起作用?Rockcissorpaper 游戏的部分代码
- php - 如何将 base64 编码图像上传到 S3 存储桶 php codeigniter
- sql - 尝试从访问表中删除重复记录
- json - 在 ResponseEntity 中发送变量
- azure - Azure Log Analytics 通过工作区 id 和 PRIMARY KEY 使用 rest api 查询/获取数据
- javascript - 如何将javascript(正则表达式)字符串与另一个忽略字符串顺序的字符串进行比较/匹配/替换
- arrays - 无法从解析的 JSON 中获取字段值