Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
There is a list of objects in list1. I want if each object in list1 there was in list2 too then that object will be deleted from list2.the problem is after removing, list2 still contains that object!!!
C#
 foreach (var item in list1)
{
  
if (list2.Any(x => x.Vacationfrom == item.Vacationfrom && x.VacationTo == item.VacationTo && x.WhenIsVac == item.WhenIsVac && x.TheDay == item.TheDay))
                       
        list2.Remove(item);
}
Posted

You're trying to remove the item that comes from list1 from list2. You would have to find the actual item from list2 that matches the item from list1 and remove that:
C#
foreach (var item in list1)
{
    var item2 = list2.SingleOrDefault(x => x.Vacationfrom == item.Vacationfrom && x.VacationTo == item.VacationTo && x.WhenIsVac == item.WhenIsVac && x.TheDay == item.TheDay);
    if(item2 != null)
        list2.Remove(item2);
}
 
Share this answer
 
item is in list1; not in list2.


You might want something like list1 = list1.Except ( ... )

https://msdn.microsoft.com/en-us/library/bb336390(v=vs.110).aspx[^]
 
Share this answer
 
v2
Because
var item

does not exists in list2, is a list1's item. You can use a for inside a for.
For each item in list1 you look all itens in list2 and, if the current item in list1 is equal the current item in list2, you remove that item and break the internal for and go to the next loop of the first for.
 
Share this answer
 
When list1 and list2 are not mixed up, just think at this: the code when you traverse the collection in not strictly specified order and modify the set or elements at the same time (add, remove) is potentially incorrect. How to you know what you are traversing after each iteration? For removal, it does not happen if you remove while traversing the elements in reverse, using integer indices and going from higher indices to lower. Isn't it obvious?

And of course, it's better to use available method or extension methods of collections, as well as LINQ: https://msdn.microsoft.com/en-us/library/bb397919.aspx[^].

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900