2010-10-13 80 views
3
foreach (Feature fe in features) 
{ 
    if (fileNames.Any(file => file.Contains(fe.FeatureName))) 
    { 
     fe.MatchCount = fe.MatchCount == 0 ? 1 : fe.MatchCount; 
    } 
} 

回答

1

東西值得一提的是,隨着「的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); 
3
features.Where(f => fileNames.Any(file => file.Contains(f.FeatureName))) 
     .ToList() 
     .ForEach(x => x.MatchCount = x.MatchCount == 0 ? 1 : x.MatchCount); 
+0

這會不會扔收藏」異常被修改;枚舉操作可能不會執行 – Younes 2010-10-13 07:14:14

+0

@Younes:?集合不修改集合中的對象的屬性被修改(或者會;看起來這個任務是缺失的),但是集合本身沒有被修改 – 2010-10-13 07:15:46

+0

@Younes:是嗎?這是一個記事本代碼,我沒有嘗試,但我認爲它不會拋出異常,因爲我首先將其轉換爲ToList,修改是基於列表 – 2010-10-13 07:17:14

9

您是變異對象在循環變量的結束,所以你不能在 LINQ做(乾淨)。只需保持循環;這將是容易理解的,但也許它可以減少

var qry = features.Where(fe => fe.MatchCount == 0 && 
      fileNames.Any(file => file.Contains(fe.FeatureName)); 

foreach (Feature fe in qry) { fe.MatchCount == 1; } 
+10

+1我不明白爲什麼人們不喜歡'foreach(blabla)',他們總是比較喜歡單線linq表達式,它比'foreach'循環。 – 2010-10-13 07:15:26

+1

對答案+1(和@ Danny的評論) – 2010-10-13 07:16:38

+2

也調試linq查詢是一個痛苦。 – Jake 2010-10-13 07:23:37

0
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);