LINQ Single() Exception for 0 or multiple items

前端 未结 2 649
抹茶落季
抹茶落季 2020-12-31 00:16

I have some IEnumberable collection of items. I use .Single() to find a specific object in the collection.

I choose to use Single()

相关标签:
2条回答
  • 2020-12-31 00:44

    I wouldn't recommend using the try/catch in this scenario, because using exceptions to make logical decisions is resource expensive.

    I would recommend using SingleOrDefault(), and check if the result is null. If it is. Do your creation.

    0 讨论(0)
  • 2020-12-31 00:50

    What you want is SingleOrDefault()

    The "or default" actually means it returns null (for reference types) or whatever the default would be for a non-reference type. You'll need to new-up an object to take its place.

    0 讨论(0)
提交回复
热议问题