Reputation: 14472
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
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
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
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