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

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

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

MSDN documents that SingleOrDefault:

15条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 13:12

    Whenever you use SingleOrDefault, you clearly state that the query should result in at most a single result. On the other hand, when FirstOrDefault is used, the query can return any amount of results but you state that you only want the first one.

    I personally find the semantics very different and using the appropriate one, depending on the expected results, improves readability.

提交回复
热议问题