A sequence contains more than one element - SingleOrDefault does not help

I have the line below, but still get the exception " The sequence contains more than one element "

Details rd = this.db.Details.SingleOrDefault(x => x.TId == Id && x.TypeId == TypeId); 

I was hoping that SingleOrDefault would avoid the exception.

+7
c # linq-to-entities
source share
2 answers

SingleOrDefault returns a SINGLE element or null if the element is not found. If 2 elements are found in your Enumerable, they raise an exception that you see. Just like Highlander ... with Single - there can only be one.

FirstOrDefault returns the FIRST element that it finds or null if the element is not found. therefore, if there are two elements that match your predicate, the second is ignored.

Assuming you don't care if there are several matches, and you only need the first or zero if no match is found ... then you probably need the following ...

 Details rd = this.db.Details .FirstOrDefault(x => x.TId == Id && x.TypeId == TypeId); 

Note that both of these methods return only one element, they differ only in what they do after they find a match. First stops looking at this point and returns the result, Single continues to check the rest of the list to make sure there are no more matches. The OrDefault part determines what it returns if no match is found. SingleOrDefault or FirstOrDefault returns null if the value is not found, but if you just use Single or First , then it MUST find one match, otherwise it throws an exception.

EDIT: Good point. Steve Since First returns the first item, you may need to use OrderBy to make sure the item you want is indeed the first. For example ... suppose your object had an UpdateDate property, and you wanted the object to have the latest UpdateDate ...

 Details rd = this.db.Details .OrderByDescending(x => x.UpdateDate) .FirstOrDefault(x => x.TId == Id && x.TypeId == TypeId); 
+19
source share

If you have a list, convert the list to an IEnumerable list, then you can use the FirstOrDefault method

  IEnumerable<BuyOnlineSearchdetails> details = new List<BuyOnlineSearchdetails>(); var FirstRow = details.FirstOrDefault(); string Count = "0"; if (FirstRow != null) { Count = FirstRow.TotalCount.ToString(); } else { Count = "0"; } 
0
source share

All Articles