简体   繁体   中英

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>();

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);

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);
                }
            }

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM