1

I am making a program that puts different participants in a library with a particular key. I came to the problem where I got a KeyNotFoundException.

Here you can see my code error which was at if (sessionPersonsSchedule[s].Count == s.MaxParticipants)

public bool personAddToLibrary(int personsIn)
{   
    if (personsIn == participants.Count)
    {
        return true;
    }
    else
    {
        for ( int j = 0; j < participants[personsIn].Preferences.Count; j++ )
        {
            Participant p = participants[personsIn];
            Session s = sessions[p.Preferences[j] - 1];
            SessionPersonsSchedule[s]
            if (testSessions(s))
            {
                sessionPersonsSchedule[s].Add(p);
                Console.Write(personsIn + ". " + p + "is added to session " + s);
                personAddToLibrary(personsIn + 1);
                if (personsIn == participants.Count)
                {
                    return true;
                }
            }
            else
            {
                sessionPersonsSchedule[s].Remove(p);
                Console.Write(personsIn + ". " + p + "is deleted from session " + s);
            }
        }
    }
    return false;
}
public bool testSessions(Session s)
{
    if (sessionPersonsSchedule[s].Count == s.MaxParticipants)
    {
        return false;
    }
    else
    {
        return true;
    }
}
jaredk
  • 986
  • 5
  • 21
  • 37
sansactions
  • 215
  • 5
  • 17
  • See here: http://stackoverflow.com/questions/606636/best-way-to-handle-a-keynotfoundexception – Vova Oct 05 '15 at 15:38

1 Answers1

0

The KeyNotFoundException indicates that you are trying to index into the collection with a key that doesn't exist in the collection.

So, before you do sessionPersonsSchedule[s] in testSessions, you can make sure that s exists first by calling Dictionary.ContainsKey.

ama1111
  • 569
  • 3
  • 10