Posts

Showing posts from April, 2010

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