ListOfFruits.FirstOrDefault(x => x.Name == "Apple").ID
You could also load the FirstOrDefault into an object and check for null before trying to access the id.
As suggested, in order to avoid a NullRef exception you can do a couple of things:
If you are using a version of VS with the Roslyn compiler:
ListOfFruits.FirstOrDefault(x => x.Name == "Apple")?.ID
Otherwise the more verbose method:
var fruit = ListOfFruits.FirstOrDefault(x => x.Name == "Apple");
if (fruit != null)
{
return fruit.ID;
}
return 0;
This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First(). Single expects a single response that has to be there, I find myself gravitating to FirstOrDefault more often than not.