[CSHARP-846] Take(1).SingleOrDefault() throws InvalidOperationException Created: 18/Oct/13  Updated: 05/Apr/19  Resolved: 22/Apr/15

Status: Closed
Project: C# Driver
Component/s: Linq
Affects Version/s: 1.8.3
Fix Version/s: 2.1

Type: Task Priority: Minor - P4
Reporter: Paul Bowden Assignee: Unassigned
Resolution: Done Votes: 1
Labels: question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Window 7 64 bit


Attachments: Text File Program.cs    
Epic Link: Rewrite Linq

 Description   

The attached code throws an InvalidOperationException() - Sequence contains more than one element, but there is only one element due to the Take(1) ?

I can easily work around this issue, but is this a bug or by design?

var result = collection.AsQueryable().Where( m => m.Name == "Lisa" ).Take( 1 ).SingleOrDefault(); // exception thrown here



 Comments   
Comment by Craig Wilson [ 22/Apr/15 ]

This has been fixed with CSHARP-601.

Comment by Robert Stam [ 22/Oct/13 ]

In case anyone is wondering what the easy workaround is, this is it:

// replace
var result = collection.AsQueryable().Where( m => m.Name == "Lisa" ).Take( 1 ).SingleOrDefault();
// with
var result = collection.AsQueryable().Where( m => m.Name == "Lisa" ).FirstOrDefault()

Comment by Craig Wilson [ 18/Oct/13 ]

Interesting problem. This is definitely a bug. So, the issue is that to do Single() or SingleOrDefault(), we have to select 2 items in order to throw an exception if there is more than 1, just like Linq to Objects does. Therefore, that Take(1) get's ignored.

As you said, this should be trivial to work-around, but we'll get this fixed. Thanks for the report.

Generated at Wed Feb 07 21:38:00 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.