如何通过LINQ使用以下代码来避免循环?

时间:2010-10-13 06:58:14

标签: c# linq

foreach (Feature fe in features)
{
    if (fileNames.Any(file => file.Contains(fe.FeatureName)))
    {
        fe.MatchCount = fe.MatchCount == 0 ? 1 : fe.MatchCount;
    } 
}

4 个答案:

答案 0 :(得分:9)

你是在循环变量的末尾变异对象,所以你不能在 pure 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 :(得分:3)

features.Where(f => fileNames.Any(file => file.Contains(f.FeatureName)))
        .ToList()
        .ForEach(x => x.MatchCount = x.MatchCount == 0 ? 1 : x.MatchCount);

答案 2 :(得分:1)

值得一提的是,如果您的列表非常大,将查询实现到列表,然后使用'ForEach'再次迭代它可能是一个非常昂贵的调用。我建议添加以下扩展方法,为IEnumerable提供'ForEach'方法:

public static void Map<T>(this IEnumerable<T> source, Action<T> func)
{
    foreach (T i in source)
        func(i);
}

我称之为地图,但如果您愿意,可以将其称为ForEach。这将Danny的答案变为:

features.Where(f => fileNames.Any(file => file.Contains(f.FeatureName)))
        .Map(x => x.MatchCount = x.MatchCount == 0 ? 1 : x.MatchCount);

答案 3 :(得分: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);