Q:

C# more elegant replacement for foreach-search

Here is the entirety of a method inside a class:
public Foo GetFooByInfoName(string name)
{
    Debug.Assert(name != null, "name is not an optional argument");
    foreach (Foo f in storedFoos.Values)
    {
        if (name.Equals(f.FooInfo.Name))
        {
            return f;
        }
    }
    return null;
}

I have obviously changed the names, so assume FooInfo is required and Name can't simply be a property of the class Foo.
Is there a more elegant way to write this method? I'm not very familiar with C# but I feel like there's an extension method or something which can turn this method into a 2-liner.
Note I'm looking for readability, it's not a contest to reduce the number of lines. I simply think the method would be more clear if C# had a way to search for the named Foo in one line.
(I'm using C# 3.5)

A:

return storedFoos.FirstOrDefault(f => name == f.FooInfo.Name);
You'll need to make sure that your are using System.Linq.
By the way, C# overrides the == operator for strings, so it's usually easier to use == instead of .Equals (much more readable, and idiomatic C#).

