In Linq, what's the difference between .FirstOrDefault and .SingleOrDefault
I don't know the differe开发者_JS百科nce between FirstOrDefault
and SingleOrDefault
. When should I use the first and when should I use the second?
FirstOrDefault()
is for when zero or more results are expected to be present in the input collection and the call returns the first item if there are multiple results, Default if none.
SingleOrDefault()
is for when zero or one result is expected in the input collection and the call returns the one result if exactly one result is present, Default if no results and exception if more than one result.
SingleOrDefault will throw a "Sequence contains more than one element" exception if more than one item exists.
firstordefault it will take number of rows but will just return first one of it if it is null it can handle the exception First it will take number of rows but will just return first one of it if it is null it will throw the exception singleordefault it will take only one row but will return it can handle exceptions if it is null single it will take only one row but will return it & cannot handle exceptions
If your result set returns 0 records:
SingleOrDefault returns the default value for the type (e.g. default for int is 0) FirstOrDefault returns the default value for the type If you result set returns 1 record:
SingleOrDefault returns that record FirstOrDefault returns that record If your result set returns many records:
SingleOrDefault throws an exception FirstOrDefault returns the first record Conclusion:
If you want an exception to be thrown if the result set contains many records, use SingleOrDefault.
If you always want 1 record no matter what the result set contains, use FirstOrDefault
精彩评论