views:

54

answers:

5

Im getting error whenever i fetch like this

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

because this can return one or more than one element. so what is the alternative approach that i can use to solve this issue

+6  A: 

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);
spender
+2  A: 

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.)

Jon Skeet
+1  A: 

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.

DaveShaw
+1  A: 

SingleOrDefault suggests that you are expecting 0 or 1 results from your query. If you have more than 1 then there is something wrong with your data or query.

If you are expecting more than 1 result and only want the first one, then FirstOrDefault should be used.

geoff
+1  A: 

If you are using SingleOrDefault if the condition satisfy more than result it will throw error.

you can achieve your result by using FirstOrDefault

anishmarokey