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
?
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
?
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 ?.
.
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 c# .net linq
You are not signed in. Login or sign up in order to post.
what would the default value be? It does not measure a NULL?
– mcamara
I put a link, not necessarily null, can be a 0.
– Maniero
cool @bigown will look calmly the link!
– mcamara