- Use
SingleOrDefault()
if 0 or 1 items are expected
- Use
Single()
if 1, not 0 or 2 and more, item is expected
Also keep in mind that there are a number of possible scenarios:
- You got 0 when 0 or 1 was expected (ok)
- You got 1 when 0 or 1 was expected (ok)
- You got 2 or more when 0 or 1 was expected (error)
And:
- You got 0 when 1 was expected (error)
- You got 1 when 1 was expected (ok)
- You got 2 or more when 1 was expected (error)
And don't forget about First()
, FirstOrDefault()
and Any()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…