Another Linq translation question
Ok, so I'm iterating a collection. for each member that meets some criteria, I want to call a method on that member:
Here's how I'm doing it now:
foreach(MyObject obj in myCollection)
{
if(obj.Property == theSearchValue)
obj.DoIt();
}
For what it's worth, I think that the foreach is the most readable, clear way to do this (we could talk fine points about curly braces), so 开发者_StackOverflow社区this is more of an academic/learning question for me.
The question: What's the best way to express that with Linq? Is there a Linqy way to do this that is more clear/readable/maintainable than my foreach loop? If so, does it do so without sacrificing performance?
(alot of the linq operations that I see look neat and all, but they often result in the creation of intermediate enumerables, or sometimes enumerating a collection multiple times -- my little foreach solves the problem in 1 pass, with no temporary collections created.)
You won't gain much from using LINQ...
var matches = myCollection.Where(i => i.Property == theSearchValue);
foreach(var item in matches)
item.DoIt();
You could also use Extension Methods to add an Each()
method to hide the loop (but you won't gain efficiency). The resulting code would look like:
myCollection.Where(i => i.Property == theSearchValue).Each(i => i.DoIt());
foreach (MyObject obj in
myCollection.Where(item => item.Property == theSearchValue))
obj.DoIt();
精彩评论