How to ask “Is there exactly one element satisfying condition” in LINQ?

后端 未结 4 938
庸人自扰
庸人自扰 2021-01-01 14:40

Quick question, what\'s the preferable way to programmaticaly ask \"Is there exactly one element in this sequence that satisfies X condition?\" using Linq?

i.e.

4条回答
  •  清酒与你
    2021-01-01 14:50

    The simplest way is to just use Count. Single won't work for you, because it throws an exception if there isn't just that single element.

    LBushkin suggests (in the comments) to use SequenceEqual to compare a sequence with another one. You could use that by skipping the first element with Skip(1), and comparing the resulting sequence to an empty sequence such as what you can get from Empty

提交回复
热议问题