Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

foreach (Feature fe in features)
{
    if (fileNames.Any(file => file.Contains(fe.FeatureName)))
    {
        fe.MatchCount = fe.MatchCount == 0 ? 1 : fe.MatchCount;
    } 
}
like image 908
Shawn Avatar asked Jun 13 '26 11:06

Shawn


1 Answers

You are mutating the object at the end of the loop-variable, so you can't do that (cleanly) in pure 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; }
like image 91
Marc Gravell Avatar answered Jun 16 '26 22:06

Marc Gravell