How to avoid loop 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;
    } 
}
+3
source share
4 answers

Something worth mentioning is that materializing your request into a list and then repeating it again with "ForEach" can be quite an expensive call if your list is large enough. I would recommend adding the following extension method to give the "ForEach" method for IEnumerable:

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

I call my card, but you can call it ForEach if you decide so. This turns Danny into:

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

, () LINQ. ; , , , :

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

foreach (Feature fe in qry) { fe.MatchCount == 1; }
+9
features.Where(f => fileNames.Any(file => file.Contains(f.FeatureName)))
        .ToList()
        .ForEach(x => x.MatchCount = x.MatchCount == 0 ? 1 : x.MatchCount);
+3
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);
0

Source: https://habr.com/ru/post/1769287/


All Articles