SingleOrDefault() throws an exception on more than one element

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

    Single and SingleOrDefault are designed to throw if more that one match exists in the sequence. A consequence of this is that the entire sequence must be iterated prior to completion. It does not sound like this is what you want. Try FirstOrDefault instead:

    Feature f = o.Features
        .FirstOrDefault(e => e.vcr_LinkName == PageLink && e.bit_Activate == true);
    

    This will (generally) perform better because it completes as soon as a match is found.

    Of course, if you actually want to retain more than one element, a Where clause would be more appropriate:

    IEnumerable fs = o.Features
        .Where(e => e.vcr_LinkName == PageLink && e.bit_Activate == true);
    

提交回复
热议问题