LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

前端 未结 15 1235
我在风中等你
我在风中等你 2020-11-22 12:48

Consider the IEnumerable extension methods SingleOrDefault() and FirstOrDefault()

MSDN documents that SingleOrDefault:

15条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 13:18

    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

提交回复
热议问题