Search code examples
linqlinq-to-sqlcollections

SingleOrDefault() throws an exception on more than one element


I'm getting an exception whenever I fetch like this

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

because this can return one or more than one element. What is the alternative approach that I can use to solve this issue?


Solution

  • 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<Feature> fs = o.Features
        .Where(e => e.vcr_LinkName == PageLink && e.bit_Activate == true);