foreach (Feature fe in features)
{
if (fileNames.Any(file => file.Contains(fe.FeatureName)))
{
fe.MatchCount = fe.MatchCount == 0 ? 1 : fe.MatchCount;
}
}
回答
東西值得一提的是,隨着「的ForEach再次物化查詢到一個列表,然後再遍歷它'如果你的名單很大,可能是一個非常昂貴的電話。我會建議增加以下擴展方法送「的ForEach」方法的IEnumerable:
public static void Map<T>(this IEnumerable<T> source, Action<T> func)
{
foreach (T i in source)
func(i);
}
我叫我的地圖,但你可以調用它的ForEach,如果你選擇。這將打開丹尼的回答到:
features.Where(f => fileNames.Any(file => file.Contains(f.FeatureName)))
.Map(x => x.MatchCount = x.MatchCount == 0 ? 1 : x.MatchCount);
features.Where(f => fileNames.Any(file => file.Contains(f.FeatureName)))
.ToList()
.ForEach(x => x.MatchCount = x.MatchCount == 0 ? 1 : x.MatchCount);
您是變異對象在循環變量的結束,所以你不能在純 LINQ做(乾淨)。只需保持循環;這將是容易理解的,但也許它可以減少位:
var qry = features.Where(fe => fe.MatchCount == 0 &&
fileNames.Any(file => file.Contains(fe.FeatureName));
foreach (Feature fe in qry) { fe.MatchCount == 1; }
+1我不明白爲什麼人們不喜歡'foreach(blabla)',他們總是比較喜歡單線linq表達式,它比'foreach'循環。 – 2010-10-13 07:15:26
對答案+1(和@ Danny的評論) – 2010-10-13 07:16:38
也調試linq查詢是一個痛苦。 – Jake 2010-10-13 07:23:37
Func<Feature, Feature> updateMatchCount = (fe) =>{
fe.MatchCount = fe.MatchCount == 0 ? 1 : fe.MatchCount;
return fe;
};
var updatedFeatures = from fe in features
where fileNames.Any(file => file.Contains(fe.FeatureName))
select updateMatchCount(fe);
- 1. 如何通過避免循環來優化這個t-sql腳本代碼?
- 2. 如何避免重複以下代碼?
- 3. 如何重構代碼以避免Java循環中的標籤?
- 4. 在Python代碼循環,以避免重複和減少代碼
- 5. 如何使用LINQ創建數據庫查詢通過使用ID列表和避免循環來刪除行
- 6. 避免循環後重復代碼?
- 7. 如何避免在Linq to Sql查詢中循環循環?
- 8. 如何避免使用numpy for循環?
- 9. 如何避免使用Spark循環?
- 10. 如何避免循環
- 11. 如何避免infinte循環
- 12. 通過使用應用函數避免for循環
- 13. 避免循環
- 14. 如何避免循環外的執行代碼
- 15. Python 2.7版:如何使用避免循環的多個迭代
- 16. 如何通過StringBuilder避免Java OutofMemoryError堆空間循環?
- 17. EF6:如何避免循環引用?
- 18. 模式,以避免循環調用
- 19. 如何避免通過數組循環來找到部分匹配?
- 20. PHP - 如何通過htaccess來避免重定向中的無限循環
- 21. 如何重構此JavaScript代碼以避免在循環中生成函數?
- 22. 避免for循環
- 23. 避免循環iframe
- 24. 避免while循環
- 25. 如何避免在代碼中運行代碼幾行代碼時使用for循環R
- 26. 有沒有辦法避免循環使代碼更快?
- 27. 避免通過使用jQuery
- 28. 避免使用讓關鍵字做自我循環的LINQ
- 29. 如何通過在這種情況下使用lambda或linq來避免使用嵌套的foreach語句?
- 30. 以純代碼避免IORefs
這會不會扔收藏」異常被修改;枚舉操作可能不會執行 – Younes 2010-10-13 07:14:14
@Younes:?集合不修改集合中的對象的屬性被修改(或者會;看起來這個任務是缺失的),但是集合本身沒有被修改 – 2010-10-13 07:15:46
@Younes:是嗎?這是一個記事本代碼,我沒有嘗試,但我認爲它不會拋出異常,因爲我首先將其轉換爲ToList,修改是基於列表 – 2010-10-13 07:17:14