tags:

views:

72

answers:

2

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 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.)

+4  A: 

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());
Justin Niessner
+2  A: 
foreach (MyObject obj in 
                    myCollection.Where(item => item.Property == theSearchValue))
    obj.DoIt();
DreamWalker
I like the clarity on this one. But do you know whether the "where" extension is one of the extensions that executes all at once, or whether it is a yield? (eg: is that code executing 2 loops or 1 loop?)
JMarsch
@JMarsch, Everything is ok, only 1 loop. Go to IL for proof
DreamWalker
@DreamWalker: I really like your answer and Justin's I thought that yours was the most readable, so I marked yours as the answer. Thanks for all the help guys!
JMarsch