Another Linq Translation Issue

So, I repeat the collection. for each member that meets some criteria, I want to call a method for this member:

Here's how I do it now:


foreach(MyObject obj in myCollection)
{
  if(obj.Property == theSearchValue)
    obj.DoIt();
}

For what it's worth, I think that foreach is the most readable, understandable way to do this (we could talk about curly brace points), so for me this is a more academic / educational question.

Question: What is the best way to express this with Linq? Is there a Linqy way to make this more understandable / readable / supported than my foreach loop? If so, does it do so without sacrificing performance?

(many of the linq operations that I see look neat and all, but they often lead to creating intermediate enumerations or sometimes enumerating the collection several times - my little foreach solves the problem in 1 pass without temporary created collections.)

+3
source share
2 answers
foreach (MyObject obj in 
                    myCollection.Where(item => item.Property == theSearchValue))
    obj.DoIt();
+2
source

You won’t get much from using LINQ ...

var matches = myCollection.Where(i => i.Property == theSearchValue);

foreach(var item in matches)
    item.DoIt();

You can also use extension methods to add a method Each()to hide the loop (but you will not get efficiency). The resulting code will look like this:

myCollection.Where(i => i.Property == theSearchValue).Each(i => i.DoIt());
+5
source

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


All Articles