"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

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

Silent Renew and the "login_required" Error When Using oidc-client

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

How to Determine if a Column Exists in a DataReader