为什么这个删除列表dosnt的方法工作? [英] why this remove method of list dosnt work?
问题描述
list1中有一个对象列表。我想如果list1中的每个对象都在list2中,那么该对象将从list2中删除。问题是在删除后,list2仍然包含该对象!!!
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!!!
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);
}
推荐答案
您正在尝试从list2中删除list1中的项目。您必须从list2中找到与list1中的项匹配的实际项并删除它:
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:
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);
}
item
位于list1
;不在list2
。
您可能需要类似<$ c $的东西c> list1 = list1.Except(...)
https://msdn.microsoft.com/en-us/library/bb336390(v = vs.110)的.aspx [< a href =https://msdn.microsoft.com/en-us/library/bb336390(v=vs.110).aspx\"target =_ blanktitle =New Window> ^ ]
item
is inlist1
; not inlist2
.
You might want something likelist1 = list1.Except ( ... )
https://msdn.microsoft.com/en-us/library/bb336390(v=vs.110).aspx[^]
因为
var item
$ b $ c> list2中不存在
,是 list1
的项目。您可以在里面使用for for。
对于 list1
中的每个项目,你在 list2中看起来都是
并且,如果 list1
中的当前项目等于 list2
中的当前项目,则删除该项目并打破内部for并转到第一个for的下一个循环。
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.
这篇关于为什么这个删除列表dosnt的方法工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!