我從Linq查詢返回一個列表,之後我必須用for循環填充它中的值。 問題是它太慢了。查詢和foreach的Linq優化
var formentries = (from f in db.bNetFormEntries
join s in db.bNetFormStatus on f.StatusID.Value equals s.StatusID into entryStatus
join s2 in db.bNetFormStatus on f.ExternalStatusID.Value equals s2.StatusID into entryStatus2
where f.FormID == formID
orderby f.FormEntryID descending
select new FormEntry
{
FormEntryID = f.FormEntryID,
FormID = f.FormID,
IPAddress = f.IpAddress,
UserAgent = f.UserAgent,
CreatedBy = f.CreatedBy,
CreatedDate = f.CreatedDate,
UpdatedBy = f.UpdatedBy,
UpdatedDate = f.UpdatedDate,
StatusID = f.StatusID,
StatusText = entryStatus.FirstOrDefault().Status,
ExternalStatusID = f.ExternalStatusID,
ExternalStatusText = entryStatus2.FirstOrDefault().Status
}).ToList();
,然後我以這種方式使用的:
for(var x=0; x<formentries.Count(); x++)
{
var values = (from e in entryvalues
where e.FormEntryID.Equals(formentries.ElementAt(x).FormEntryID)
select e).ToList<FormEntryValue>();
formentries.ElementAt(x).Values = values;
}
return formentries.ToDictionary(entry => entry.FormEntryID, entry => entry);
但絕對是太慢了。 有沒有辦法讓它更快?
每次調用formentries.Count和formentries.ElementAt都會再次執行基礎查詢。你應該緩存查詢結果,並通過在Formentries上調用ToArray或ToList(在保存結果之前)對其進行操作,然後再通過Formentries執行你的邏輯 – Polity 2012-02-29 15:06:07
@Polity它已經物化的查詢 – 2012-02-29 15:13:30
請不要在「C# 「等等。這就是標籤的用途。 – 2012-02-29 15:13:39