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

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

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

MSDN documents that SingleOrDefault:

15条回答
  •  盖世英雄少女心
    2020-11-22 13:17

    I queried Google for the usage of the different methods on GitHub. This is done by running a Google search query for each method and limiting the query to the github.com domain and the .cs file extension by using the query "site:github.com file:cs ..."

    It seems that the First* methods are more commonly used than the Single* methods.

    | Method               | Results |
    |----------------------|---------|
    | FirstAsync           |     315 |
    | SingleAsync          |     166 |
    | FirstOrDefaultAsync  |     357 |
    | SingleOrDefaultAsync |     237 |
    | FirstOrDefault       |   17400 |
    | SingleOrDefault      |    2950 |
    

提交回复
热议问题