简体   繁体   English

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

[英]How to avoid loop by using LINQ for the following code?

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

You are mutating the object at the end of the loop-variable, so you can't do that (cleanly) in pure LINQ. 你正在改变循环变量末尾的对象,所以你不能在 LINQ中这样做(干净利落)。 Just keep the loop; 保持循环; it'll be simpler to understand, but maybe it can be reduced a bit : 理解起来会更简单,但也许可以减少一点

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

foreach (Feature fe in qry) { fe.MatchCount == 1; }
features.Where(f => fileNames.Any(file => file.Contains(f.FeatureName)))
        .ToList()
        .ForEach(x => x.MatchCount = x.MatchCount == 0 ? 1 : x.MatchCount);

Something worth mentioning is that materializing your query to a list, and then iterating over it again with 'ForEach' can be a pretty expensive call if your list is quite large. 值得一提的是,如果您的列表非常大,将查询实现到列表,然后使用'ForEach'再次迭代它可能是一个非常昂贵的调用。 I would recommend adding the following extension method to give a 'ForEach' method to IEnumerable: 我建议添加以下扩展方法,为IEnumerable提供一个'ForEach'方法:

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

I call mine Map, but you can call it ForEach if you so choose. 我称之为地图,但如果您愿意,可以将其称为ForEach。 This turns Danny's answer into: 这将Danny的答案变为:

features.Where(f => fileNames.Any(file => file.Contains(f.FeatureName)))
        .Map(x => x.MatchCount = x.MatchCount == 0 ? 1 : x.MatchCount);
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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM