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] (IEnumerable1 source, Int32 initValue, System.Func3 selector)
System.Linq.Enumerable.Max (IEnumerable1 source) GameManager.addActor (UnityEngine.GameObject actor) (at Assets/Scripts/GameManager.cs:121) Team.CreateTeam (System.String teamName, System.Collections.Generic.List1 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?

Looks like the problem is that the .Max() extension function doesn’t know what to do with a single-element list.