This code works:
public SiteMapping GetById(int ID)
{
var entity = siteMappings.First(p => p.Id == ID);
return entity == null ? null : entity;
}
...and so does this (with the same result):
public SiteMapping GetById(int ID)
{
var entity = siteMappings.Find(p => p.Id == ID);
return entity == null ? null : entity;
}
Is there a reason to prefer one (First, or Find) over the other?
So, using Reed's suggestion, all I need is this:
public SiteMapping GetById(int ID)
{
return = siteMappings.FirstOrDefault(p => p.Id == ID);
}
...and it's safe / it fails gracefully (or not at all, of course, when provided a proper ID val).
First
will raise an exception if the object is not found. FirstOrDefault
would be more similar to Find
. Note that, in your first example, the null check (which should be eliminated, and just written as return entity;
, as the ternary is not useful) will never happen if the Id
is not found, as the method will raise an exception.
FirstOrDefault
is an extension method on IEnumerable<T>
or IQueryable<T>
, which means that it will work in more scenarios than a Find
method, which is a method defined on a specific class.
If this is List<T>.Find
, both FirstOrDefault
and Find
will be O(n) and have basically the same performance, so there is no definitive advantage to either. I'd generally prefer FirstOrDefault
just for the fact that it's a bit more flexible, and would allow you to change the collection type without having to change your method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With