FirstOrDefault, SingleOrDefault, ElementAtOrDefault [duplicate]

1

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

    
asked by anonymous 19.09.2017 / 16:47

2 answers

4

Versions without Default generate exception if it finds zero elements in the adopted criteria, so it should be used when it is certain that it has at least one element. That is, if it has zero elements it is a programming error and should be fixed or something exceptional and should be handled (rarer than most imagine).

With Default it will return the default value of that type waits if it does not find anything, and obviously does not generate exception. It can even be a null if it's types by reference, but can be a value of zero in other types. That is, "nothing" is expected, and this should be dealt with later, probably with a if or equivalent, something like ?? or ?. .

    
19.09.2017 / 16:50
3

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

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

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