Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

268
Vistas
LINQ Any() and Single() vs. SingleOrDefault() with null check

In what cases is each solution preferred over the other?

Example 1:

if (personList.Any(x => x.Name == "Fox Mulder"))
{
  this.Person = personList.Single(x => x.Name == "Fox Mulder");
}

Example 2:

var mulder = personList.SingleOrDefault(x => x.Name == "Fox Mulder");

if (mulder != null)
{
  this.Person = mulder;
}
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Both Single and SingleOrDefault will enumerate the collection beyond the first matching result to verify that there is exactly one element matching the criteria, stopping at either the next match or the end of the collection. The first example will be slightly slower, since the Any call will enumerate enough of the collection (possibly all of it) to determine whether any elements meet the criteria, stopping at either the first match or the end of the collection.

There is one other critical difference: the first example could throw an exception. Single will return the matching element if there is exactly one, and throw an exception otherwise. Checking with Any does not verify this; it only verifies that there is at least one.

Based one these two reasons (primarily/especially the second reason), the SingleOrDefault approach is preferable here.


So, there are three cases here.

Case 1: No items match the condition

Option 1: .Any enumerates the entire set and returns false; .Single never executes.

Option 2: .SingleOrDefault enumerates the entire set and returns null.

Options essentially equivalent.

Case 2: Exactly one item matches the condition

Option 1: Any enumerates enough of the set to find the single match (could be the first item, could be the entire set). Next, Single enumerates the entire set to find that one item and confirm that no others match the condition.

Option 2: SingleOrDefault enumerates the entire set, returns the only match.

In this case, option 2 is better (exactly one iteration, compared to (1, 2] iterations)

Case 3: More than one element matches the condition

Option 1: Any enumerates enough to find the first match. Single enumerates enough to find the second match, throws exception.

Option 2: SingleOrDefault enumerates enough to find the second match, throws exception.

Both throw exceptions, but option 2 gets there more quickly.

over 4 years ago · Santiago Trujillo Denunciar

0

Extrapolating from the is v. as guidelines:

See below, from Casting vs using the 'as' keyword in the CLR:

// Bad code - checks type twice for no reason
if (randomObject is TargetType)
{
    TargetType foo = (TargetType) randomObject;
    // Do something with foo
}

By using Any and Single, you're also checking the list twice. And the same logic would seem to apply: Not only is this checking twice, but it may be checking different things, i.e., in a multi-threaded application the list could be different between the check and the assignment. In extreme cases the item found with Any might no longer exist when the call to Single is made.

Using this logic, I would go favor example two in all cases until given proof otherwise.

over 4 years ago · Santiago Trujillo Denunciar

0

Option 3:

this.Person = personList.FirstOrDefault(x => x.Name == "Fox Mulder");

if using Entity Framework and name is the primary key, then:

this.person = db.personList.Find("Fox Mulder");

Both of these work if this.Person is null coming in, or if the person isn't found, you expect this.Person to be overwritten with null. FirstOrDefault is the fastest since it will stop at the first record that matches instead of iterating through the entire collection, but it won't throw an exception if multiple are found. The entity framework solution is even better in that case because Find will use the EF cache, possibly not even having to hit the data source at all.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda