SingleOrDefault() throws an exception on more than one element

后端 未结 7 2019
野性不改
野性不改 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

    Single means that you expect be one element in the sequence. SingleOrDefault means that you expect there to be one or zero elements in the sequence. This should be used when you want know there is one (or zero) and you want it to crash when more than one it returned.

    If you are after just one, use First (or FirstOrDefault) as suggested above, but make sure you order the data correctly.

提交回复
热议问题