- Home /
Problem with using Linq: Operation is not valid due to the current state of the object
I'm trying to build up a dictionary of my "actors" (game object characters) in a game manager.
Each actor has an integer "entityReference" used as a key in a lookup dictionary.
To do this I want to check the current lookup dictionary (_actorLookup), find the largest entityReference, and set the entity reference for the newly created actor to 1 more than the greatest reference found.
To find the right value to use for the reference, I'm trying the following:
int _ref = 0;
if (_actorLookup != null && _actorLookup.Keys != null) {
List<int> _keys = _actorLookup.Keys.ToList();
_ref = _keys.Max() + 1;
}
When I run this, I get the following error after the first actor is created:
InvalidOperationException: Operation is not valid due to the current state of the object System.Linq.Enumerable.Iterate[Int32,Int32] (IEnumerable`1 source, Int32 initValue, System.Func`3 selector) System.Linq.Enumerable.Max (IEnumerable`1 source) GameManager.addActor (UnityEngine.GameObject actor) (at Assets/Scripts/GameManager.cs:121) Team.CreateTeam (System.String teamName, System.Collections.Generic.List`1 members, System.Collections.Generic.List`1 positions) (at Assets/Scripts/Team.cs:54) GameManager.Awake () (at Assets/Scripts/GameManager.cs:49)
What is wrong with my approach?
Answer by FBones · Oct 15, 2016 at 07:58 PM
Looks like the problem is that the .Max() extension function doesn't know what to do with a single-element list.
Your answer
Follow this Question
Related Questions
How can I write and use extension methods in JS? 2 Answers
Select random object in List using Linq 1 Answer
C# Lists & Inventory Logic 0 Answers
using xml, linq, and lists 0 Answers