Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Find preferred over First, or vice versa, in LINQ? [duplicate]

Tags:

c#

linq

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?

UPDATE

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).

like image 868
B. Clay Shannon-B. Crow Raven Avatar asked Jan 22 '14 00:01

B. Clay Shannon-B. Crow Raven


1 Answers

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.

like image 145
Reed Copsey Avatar answered Oct 23 '22 13:10

Reed Copsey