C # more elegant replacement for foreach-search

Here is the entire method inside the 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've obviously changed the names, so let's assume that FooInfo is required and Name cannot just be a property of the Foo class.

Is there a more elegant way to write this method? I'm not very familiar with C #, but I feel like there is an extension method or something that can turn this method into a 2-liner.

Note. I'm looking for readability, this is not a competition to reduce the number of lines. I just think the method would be clearer if C # had a way to find the named Foo

in one line.

(I am using C # 3.5)

+3


source to share


4 answers


return storedFoos.FirstOrDefault(f => name == f.FooInfo.Name);

You need to make sure that you have 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 #).

+12


source


Have you considered LINQ?



storedFoos.FirstOrDefault( f => name.Equals (f.Name));

      

+1


source


You can use Linq:

var foo = storedFoos.FirstOrDefault(f => f.Name == f.FooInfo.Name);

      

http://msdn.microsoft.com/en-us/library/bb397926.aspx

0


source


you can use for the record, it's something like this:

public Foo GetFooByInfoName(string name)
{
    Debug.Assert(name != null, "name is not an optional argument");
    var f = storedFoos.Values.Where(x => x.FooInfo.Name == name)
                              .FirstOrDefault()//gets the first value or null
    return f;
}

      

Note. Make sure you have the using System.Linq

top.

0


source







All Articles