I have a bit of an issue finding a solution for a problem.
I have 2 lists, they have identical objects, but not the same amount of objects. So to give a quick example:
List1: Object1(ID (1), Name (James)); Object2(ID(1), Name(John)); Object3(ID (1); Name(Jane)); Object4(ID (2), Name(Carl))
List2: Object1(ID(1), Name (James)), Object2(ID(1), Name(John)), Object3(ID (2), Name(Carl))
So in above example we need to remove any object that has ID(1), leaving us with a list that only contains object(4), because we do not have the same amount of objects with the same ID number, and if this is not clear, it will not always me ID(1), it could contain ID(7), ID(15), ID(123) aswell. This is a very simplified example, in reality the lists will contain several hundred objects, but the premise is the same.
(We have to remove any object from List 1 that counts more objects with an ID number than what exists in List 2)
Apologies if this is confusing or poorly explained, I will happily try to elaborate if needed.
Thanks
CodePudding user response:
It might be not optimal but,
static List<Person> Remove(List<Person> list1, List<Person> list2)
{
Dictionary<int, int> list1_count = new Dictionary<int, int>();
Dictionary<int, int> list2_count = new Dictionary<int, int>();
List<int> Ids_to_remove = new List<int>();
foreach (var item in list1)
{
if (list1_count.ContainsKey(item.ID))
{
list1_count[item.ID] = list1_count[item.ID] 1;
}
else
{
list1_count.Add(item.ID, 1);
}
}
foreach (var item in list2)
{
if (list2_count.ContainsKey(item.ID))
{
list2_count[item.ID] = list2_count[item.ID] 1;
}
else
{
list2_count.Add(item.ID, 1);
}
}
foreach (var item in list1_count)
{
if(list2_count.ContainsKey(item.Key))
{
if(item.Value > list2_count[item.Key])
{
Ids_to_remove.Add(item.Key);
}
}
}
foreach (var item in Ids_to_remove)
{
list1.RemoveAll(X => X.ID == item);
}
return list1;
}