LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria
LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria
问题
回答1
If your result set returns 0 records:
SingleOrDefaultreturns the default value for the type (e.g. default for int is 0)FirstOrDefaultreturns the default value for the type
If you result set returns 1 record:
SingleOrDefaultreturns that recordFirstOrDefaultreturns that record
If your result set returns many records:
SingleOrDefaultthrows an exceptionFirstOrDefaultreturns 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

浙公网安备 33010602011771号