"Sequence contains more than one element" Error Using LINQ

I wrote some code today utilizing LINQ to retrieve values from an XML document, and received the following error:

"Sequence contains more than one element"

I was confused because the code I wrote was very similar to other code I've written, which works fine. Turns out the error was caused because the results of my LINQ query contained more than one object, and I was using the SingleOrDefault() method -- I wanted to retrieve only the first matching object of the results. However, what I should have been doing was using the FirstOrDefault() method. The "Sequence contains more than one element" error occurs when you use SingleOrDefault() and your results contain more than one element. In situations like this, use FirstOrDefault() instead.

Comments

Popular posts from this blog

How To Mock Out Child Components In Unit Tests of Angular 2 Code

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception