检查foreach循环中列表的相等性 - C#

时间:2015-11-16 13:46:59

标签: c#

我正在尝试检查2个字符串列表的相等性,但它不起作用。这就是我所做的:

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

列表声明:

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

3 个答案:

答案 0 :(得分:1)

您无法在 foreach 循环中修改集合,但您可以在 for 循环中执行此操作:

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

另一种可能性是循环集合的副本

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

答案 1 :(得分:0)

你的问题就在这一行:

questions.Add(groupOfQuestions);

在迭代时,您无法修改集合。

您需要创建一个可以添加匹配项的新List<List<string>>。例如:

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

答案 2 :(得分:0)

在foreach中迭代它时,无法修改

questions。建立一个新列表并在最后运行AddRange

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

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

questions.AddRange(listsToAdd);