سؤال

Ad I'm developping a project in C# I recently came over an error I can't understand.

First of all here is the core

if (CanPlay(target.Coord.X, target.Coord.Y))
{
    target.Owner = m.Player;
    this.MoveList.Push(m);
    // Groupes
    var friends = GetAround(target).FindAll(i => i.Owner == target.Owner);

    Groupe g = new Groupe { target };
    foreach (Intersection fr in friends)
    {
        g.AddRange(GetGroupe(fr));
    }
    foreach (Intersection fr in friends)
    {
        this.Groupes.Remove(GetGroupe(fr));
    }
    this.Groupes.Add(g);
}

And here is the getGroupe function that causes the problem :

Groupe GetGroupe(Intersection i)
{
    return this.Groupes.First(g => g.Contains(i));
}

So, at some random moments, when a move is done, I get the IEquatable Operation is not valid due to the current state of the object. Here is the stack trace :

InvalidOperationException: Operation is not valid due to the current state of the object
System.Linq.Enumerable.First[Groupe] (IEnumerable`1 source, System.Func`2 predicate, Fallback fallback)

System.Linq.Enumerable.First[Groupe] (IEnumerable`1 source, System.Func`2 predicate)

Assets.ObjetsDeJeu.Goban.GetGroupe (Assets.ObjetsDeJeu.Intersection i) (at Assets/ObjetsDeJeu/Goban.cs:155)
Assets.ObjetsDeJeu.Goban.PutRock (Assets.ObjetsDeJeu.Move m) (at Assets/ObjetsDeJeu/Goban.cs:142)

So the line 142 is

g.AddRange(GetGroupe(fr)); 

and 155 is

return this.Groupes.First(g => g.Contains(i));

I don't understand since the this.Groupes is only empty at the very begenning. I did a test where I checked if it was empty before looking for a group but it didn't change anything ...

هل كانت مفيدة؟

المحلول

The problem is that the call to First() with the specified predicate does not yield any result. Use FirstOrDefault instead and check for null.
Change your code as follows to fix the problem:

foreach (Intersection fr in friends)
{
    var group = GetGroupe(fr);
    if(group != null)
       g.AddRange(group);
}
foreach (Intersection fr in friends)
{
   var group = GetGroupe(fr);
   if(group != null)
     this.Groupes.Remove(group);
}


Groupe GetGroupe(Intersection i)
{
   return this.Groupes.FirstOrDefault(g => g.Contains(i));
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top