【问题标题】:How to check if two lists have the same value and remove the value from one of them如何检查两个列表是否具有相同的值并从其中一个列表中删除值
【发布时间】:2017-05-22 07:36:47
【问题描述】:

我有两个列表,一个来自用户输入,另一个来自数据库。我想检查用户是否在数据库列表中输入了一个字符串,因此从用户输入的列表中删除该字符串。我试过下面的代码

foreach (string name in listOfStudentName) 
{
  if(_studentsInDatabase.Count > 0)
  {
        foreach (string nameFromDatabase in _studentsInDatabase)
        {
             If (name == nameFromDatabase)
              {
                   listOfStudentName.RemoveAll(item => item == name); 
                   break;

              }
         }
   }
}

此代码仅删除两个列表中的第一个元素,然后引发异常System.InvalidOperationExceptiom: 'Collection was modified; enumeration may not execute.

我应该补充一点,我需要能够在删除每个重复项时通知用户,例如,在每次删除重复项后显示一个消息框“name1 was removed”。

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    当您在 foreach 中枚举项目时,您无法从集合中移除项目。

    为什么不简单(这一行替换你的整个代码):

    listOfStudentName.RemoveAll(_studentsInDatabase.Contains); 
    

    如果您需要为数据库中已经存在的每个用户名做一些事情:

    var alreadyInDatabase = listOfStudentName.Intersect(_studentsInDatabase);
    foreach (string username in alreadyInDatabase)
    {
        Console.WriteLine($"{username} was removed, it is already in the database");
    }
    
    var notInDatabase = listOfStudentName.Except(_studentsInDatabase);
    listOfStudentName = notInDatabase.ToList();
    

    【讨论】:

    • 这行得通,谢谢。但是,每次删除重复值时,我都需要通知用户。例如显示一个消息框说“Name1 已被删除,它已经在数据库中”。我将如何将其应用到您的解决方案中?
    • @VincentN.: 是_studentsInDatabase List<string> 还是数据库查询?
    • 它是一个字符串。
    • @VincentN.:看看我的第二种方法
    • 这行得通,谢谢。我不完全确定如何。我只是在学习编程。我会查找方法,看看它是如何工作的。你能告诉我为什么我被否决了吗?这将帮助我提出更好的问题。
    【解决方案2】:

    为什么要使用 foreach 循环,没有必要使用它。只需获取输入的字符串并使用 _studentsInDatabase 列表匹配该字符串。如果您匹配输入的字符串而不是从 listOfStudentName 列表中删除最后添加的项目

            List<string> listOfStudentName = new List<string>();
            List<string> _studentsInDatabase = new List<string>();
    
            listOfStudentName .Add("User 1");
            listOfStudentName .Add("User 2");
            listOfStudentName .Add("User 3");
            listOfStudentName .Add("User 4");
            listOfStudentName .Add("User 5");
    
    
    
            _studentsInDatabase .Add("User 11");
            _studentsInDatabase .Add("User 22");
            _studentsInDatabase .Add("User 23");
            _studentsInDatabase .Add("User 24");
            _studentsInDatabase .Add("User 5");
    
    
    
            var index = _studentsInDatabase .FindIndex(x => x == "User 5");
            if(index!=-1)
                listOfStudentName .RemoveAt(listOfStudentName .Count-1);
    

    或者你可以做一件事,首先匹配输入的字符串,如果你发现该字符串到数据库列表中,那么不需要将它添加到 userList 中也可以工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 2013-04-16
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      相关资源
      最近更新 更多