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

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

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

MSDN documents that SingleOrDefault:

15条回答
  •  失恋的感觉
    2020-11-22 13:30

    For LINQ -> SQL:

    SingleOrDefault

    • will generate query like "select * from users where userid = 1"
    • Select matching record, Throws exception if more than one records found
    • Use if you are fetching data based on primary/unique key column

    FirstOrDefault

    • will generate query like "select top 1 * from users where userid = 1"
    • Select first matching rows
    • Use if you are fetching data based on non primary/unique key column

提交回复
热议问题