Simon
Simon

Reputation: 14472

List lambda expression throwing InvalidOperationException for one particular query

I have this snippet.

List<Frames> FrameList;

where Frames is a class containing only primitives including a string field "ExerciseID".

...


void GetFramesForExercise(string exerciseID)

    ....

    if (exerciseID == "3.2.2") { 
       Console.Write(""); }  // quick and dirty to add a breakpoint

    if (FramesList[115].ExerciseID.Equals(exerciseID)) { 
       Console.Write(""); } // quick and dirty to add a breakpoint

    frames = (Frames)FramesList.Single(r => r.ExerciseID.Equals(exerciseID));

By putting breakpoints on the console.write statements, I am able to see that exerciseID does indeed equal "3.2.2" and that FramesList[115] points to an instance of Exercise with ID equal to "3.2.2". The instance pointed to is correctly initiliased.

Why does my query throw an InvalidOperationException?

Upvotes: 0

Views: 342

Answers (4)

Adil
Adil

Reputation: 148110

FrameList may not have single instance that matches the seach criteria. Which casuse the exception in consequence.

As per msdn documentation for Enumerable.Single

Single returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence".

Upvotes: 3

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

You should First, Single is use where you expect only a single element to be returned.

frames = (Frames)FramesList.First(r => r.ExerciseID.Equals(exerciseID));

Upvotes: 0

s.meijer
s.meijer

Reputation: 3909

Instead of querying for a single item, you can also call FirstOrDefault. That call won't throw an exception in your face, when you depend on values from third party xml files.

Upvotes: 1

Rawling
Rawling

Reputation: 50114

If there are more than one matching elements, Single will throw an InvalidOperationException. (As you've checked there is at least one that matches, this is the only reason I can see that you'd get this exception.)

See the Exceptions section of this page.

Upvotes: 6

Related Questions