The question is how to get an object from List having its field value
I have got list called f_objects filled with objects.
private List<F_object> f_objects;
i’ve got also a string with some value :
string name = "something";
F_object got a method returning its field called name:
public string GetName()
{
return this.name;
}
Is there a built in method for compare objects in list vs this field value ? Or should i make a loop and compare like this:
foreach(F_object ob in f_objects)
{
if String.Equals(name, ob.GetName())
F_object found = ob;
}
There are multiple ways of doing this in linq.
First one is to use
.Where. This would suite your needs if there can be more matchesSecond option is if you are only concerned about the first hit, even if there could be more than one, in that case use
.Firstor if zero hits is an accepted situation (non-exceptional)
if you should only ever have one hit then use
.Singleor if you can have only one or zero hits then use
.SingleOrDefault