我有一個問題,建立一個相當沉重的LINQ查詢。基本上我有一種情況,我需要在循環中執行一個子查詢來過濾從數據庫返回的匹配數。實施例的代碼是在低於該循環:Linq multiple where queries
foreach (Guid parent in parentAttributes)
{
var subQuery = from sc in db.tSearchIndexes
join a in db.tAttributes on sc.AttributeGUID equals a.GUID
join pc in db.tPeopleIndexes on a.GUID equals pc.AttributeGUID
where a.RelatedGUID == parent && userId == pc.CPSGUID
select sc.CPSGUID;
query = query.Where(x => subQuery.Contains(x.Id));
}
當我隨後調用ToList()的查詢變量似乎只有所述子查詢中的單獨一個已被執行,並與數據的一桶我留下我不需要。但是這種方法的工作原理:
IList<Guid> temp = query.Select(x => x.Id).ToList();
foreach (Guid parent in parentAttributes)
{
var subQuery = from sc in db.tSearchIndexes
join a in db.tAttributes on sc.AttributeGUID equals a.GUID
join pc in db.tPeopleIndexes on a.GUID equals pc.AttributeGUID
where a.RelatedGUID == parent && userId == pc.CPSGUID
select sc.CPSGUID;
temp = temp.Intersect(subQuery).ToList();
}
query = query.Where(x => temp.Contains(x.Id));
不幸的是這種方法是討厭的,因爲它導致多個查詢到遠程數據庫,由此,如果我能得到它的工作只會導致一個命中的初步做法。有任何想法嗎?
+1如果你想了解這個概念的更多,在這裏看看飛碟雙向的答案,他引用的文章。 http://stackoverflow.com/questions/271440/c-sharp-captured-variable-in-loop – 2012-03-12 20:00:08
@DMoses感謝,我加了一些鏈接,完全承認,我無法解釋這個優雅而精確的紳士Lippert和Skeet :-) – driis 2012-03-12 21:29:50
謝謝你driis。像魅力一樣工作。你是一位聖人和一位學者先生。 – kh25 2012-03-13 09:48:44