大量数据的linq查询延迟结果
Posted
技术标签:
【中文标题】大量数据的linq查询延迟结果【英文标题】:linq query delay result for large amount of data 【发布时间】:2016-04-05 11:38:44 【问题描述】:我有一个查询,我有 5 分钟的时间来执行以下查询(总记录 40k)
var assetAssociatedEvents = (from mainNodes in projectNodes
select new OrgManagementEvent
OrgAssetsAssociatedEvent = new OrgAssetsAssociatedEvent
CustomerUID = Guid.Parse(CustomerUID),
OrgUid = Guid.Parse(mainNodes.NodeObjectUID),
AssociatedAssetUids = (from assets in customerAssets
join assetNodes in assetNodeObjects
on assets.AssetID equals assetNodes.fk_AssetID
where assetNodes.fk_NodeObjectID == mainNodes.NodeObjectID
select assets.AssetUID).Distinct().ToList().ConvertAll(Guid.Parse).ToArray(),
Timestamp = timeStampDetail
).ToList();
如果我在提高性能方面做错了什么,请您纠正我。
【问题讨论】:
你真的需要它吗?您能否在每个项目到达时进行迭代? 【参考方案1】:您是否有必要应用所有这些转换?当您调用 ToList() 时,您正在遍历整个数据集,当您调用 ConverAll 时,您正在再次执行此操作,然后您调用 ToArray 以达到相同的效果。也许您可以考虑只使用 linq 部分,然后使用 linq 查询的结果进行操作
(from assets in customerAssets join assetNodes in assetNodeObjects on assets.AssetID equals assetNodes.fk_AssetID where assetNodes.fk_NodeObjectID == mainNodes.NodeObjectID select assets.AssetUID)
我认为仅此一项就可以大大提高性能。
【讨论】:
【参考方案2】:我认为您应该拆分查询。类似的东西应该可以提高性能:
var allAssetUids = (from assets in customerAssets
join assetNodes in assetNodeObjects
on assets.AssetID equals assetNodes.fk_AssetID
select assets.AssetUID)
.Distinct()
.ToList()
.ConvertAll(Guid.Parse);
然后做
var assetAssociatedEvents = (from mainNodes in projectNodes
select new OrgManagementEvent
OrgAssetsAssociatedEvent = new OrgAssetsAssociatedEvent
CustomerUID = Guid.Parse(CustomerUID),
OrgUid = Guid.Parse(mainNodes.NodeObjectUID),
Timestamp = timeStampDetail
).ToList();
在遍历你的事件时像
foreach(var associatedEvent in assetAssociatedEvents)
AssociatedAssetUids = allAssetUids.Where(p => p == associatedEvent.NodeObjectID).ToArray();
【讨论】:
以上是关于大量数据的linq查询延迟结果的主要内容,如果未能解决你的问题,请参考以下文章
如何使用实体框架将大量数据延迟加载到 GridView [关闭]