NutCracker
NutCracker

Reputation: 12263

Checking the equality of lists in foreach loop - C#

I'm trying to check the equality of 2 lists of string but it's not working. This is what I have done:

foreach (List<string> q in questions)
{
       if (!groupOfQuestions.Except(q).Any()) //I also tried without '!'
       {
             questions.Add(groupOfQuestions);
       }
}

And declaration of lists:

List<List<string>> questions = new List<List<string>>();
List<string> groupOfQuestions = new List<string>();

Upvotes: 0

Views: 137

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186718

You can't modify collection within foreach loop, but you can do it in for loop:

  for (int i = questions.Count - 1; i >= 0; --i) {
    List<string> q = questions[i];

    if (!groupOfQuestions.Except(q).Any()) //I also tried without '!'
      questions.Add(groupOfQuestions);
  }

Another possibility is to loop on collection's copy:

  // Note ".ToList()"
  foreach (List<string> q in questions.ToList())
    if (!groupOfQuestions.Except(q).Any()) //I also tried without '!'
       questions.Add(groupOfQuestions);

Upvotes: 1

Kvam
Kvam

Reputation: 2218

questions can not be modified when iterating over it in a foreach. Build a new list and run AddRange at the end:

var listsToAdd = new List<List<string>>();

foreach (List<string> q in questions)
{
   if (!groupOfQuestions.Except(q).Any())
   {
       questions.Add(groupOfQuestions);
   }
}

questions.AddRange(listsToAdd);

Upvotes: 0

Darren Gourley
Darren Gourley

Reputation: 1808

Your problem is on this line:

questions.Add(groupOfQuestions);

You cannot modify a collection while you are iterating over it.

You're going to need to create a new List<List<string>> that you can add the matches to. For example:

            var questions = new List<List<string>> { 
                new List<string>{"aaa", "bbb", "ccc"},
                new List<string>{"aaa", "bbb", "ddd"},
            };
            var groupOfQuestions = new List<string>() { "ddd" };
            var questionMatches = new List<List<string>>();

            foreach (List<string> q in questions)
            {
                if (!groupOfQuestions.Except(q).Any()) //I also tried without '!'
                {
                    questionMatches.Add(groupOfQuestions);
                }
            }

Upvotes: 0

Related Questions