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)
source to share
you can use linq 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.
source to share