SingleOrDefault() throws an exception on more than one element

后端 未结 7 1907
野性不改
野性不改 2021-02-05 12:17

I\'m getting an exception whenever I fetch like this

Feature f = o.Features.SingleOrDefault(e => e.LinkName == PageLink);

because this can r

7条回答
  •  情书的邮戳
    2021-02-05 12:39

    If you only want the first element, use FirstOrDefault instead.

    Basically, here are the options in terms of valid results (i.e. where you don't want to throw) and what to use:

    • Exactly one: Single
    • One or zero: SingleOrDefault
    • One or more: First
    • Zero or more: FirstOrDefault

    (ElementAt and ElementAtOrDefault, Last and LastOrDefault are also available.)

提交回复
热议问题