Firstordefault, Singleordefault, Elementatordefault

Asked

Viewed 324 times

1

What is the difference between the elements FirstOrDefault and First, SingleOrDefault and Single or ElementAtOrDefault or ElementAt. When to use with and without the Default?

2 answers

5


The versions without the Default make an exception if you find zero elements in the adopted criterion, so it should be used when there is certainty that it has at least one element. That is, if it has zero elements it is a programming error and must be corrected or it is something exceptional and must be treated (rarer than most imagine).

With the Default he will return the default value than the type expects if it finds nothing, and obviously does not generate an exception. It may even be a null if it is types by reference, but can be a zero value in other types. That is, it is expected that "nothing" will come and this should be dealt with later, probably with a if or equivalent, something like the ?? or ?..

  • what would the default value be? It does not measure a NULL?

  • I put a link, not necessarily null, can be a 0.

  • cool @bigown will look calmly the link!

3

Simple, the use of Default returns a NULL value if it has no results... while the other gives an error if it does not exist and is used.

Always use with Default and do an IF validation before using, my suggestion:

var obj = lista.Where(x => x.valor = valorProcurado).FirstOrDefault();
if (obj != null) 
{
    //Executa ações
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.