Vincent N. Vincent N. -4 years ago 51
C# Question

How to check if two lists have the same value and remove the value from one of them

I have two lists, one comes from user input and the other from a database. I want to check if the user enters a string already in the database list, and hence remove that string from the list the user enters. I have tried the code below

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

}
}
}
}


This code removes only the first element that is in both lists then throws an exception
System.InvalidOperationExceptiom: 'Collection was modified; enumeration may not execute.


I should add that I need to be able to notify the user as each duplicate is removed, for example a message box saying "name1 was removed" displayed after each repetition is removed.

Answer Source

You cannot remove items from a collection while you enumerate them in a foreach.

Why not simply(this one liner replaces your whole code):

listOfStudentName.RemoveAll(_studentsInDatabase.Contains); 

If you need to do something for every user-name that was already in the database:

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download