在一个删除项目的IList<>从另外的IList<> [英] Remove items in one IList<> from another IList<>
问题描述
对不起张贴这样的基本问题,我是新来的LINQ和我试图找出这样做短暂通过每个的IList
。循环的最佳方式p>
我有2 ILists<>
自定义DTO对象。我想删除从列表在其他所有匹配项
的IList< ItemDTO> list1的= itemsbl.GetBestItems();
&IList的LT; ItemDTO>列表2 = itemsbl.GetWorstItems();
我需要删除 list1的
从列表2
。我一直在寻找的除()
方法,但显然我需要我的 ItemsDTO
类重写的GetHashCode
和等于
对于工作,但我无法找到这样的一些例子。
方法
可能有人请告诉我最好的方式来删除 list1的
从列表2
?
再次感谢
您也许可以使用除的方法来做到这一点。
VAR newList = list2.Except(list1的).ToList();
如果您想更换列表2然后就做到这一点:
列表2 = list2.Except(list1的).ToList();
从MSDN:
要比较自定义数据类型,实施IEquatable通用
接口,并提供自己的GetHashCode和等于为
型的方法。默认的相等比较,默认情况下,用于比较的实现IEquatable类型
值。
块引用>Sorry to post such basic questions, I'm new to LINQ and am trying to figure out the best way to do this short of looping through each
IList
.I have 2
ILists<>
with of custom dto objects. I want to remove all the matching items from on list that are in the other.IList<ItemDTO> list1 = itemsbl.GetBestItems(); IList<ItemDTO> list2 = itemsbl.GetWorstItems();
I need to remove all the items in
list1
fromlist2
. I have been looking at theExcept()
method but apparently i need myItemsDTO
class to override theGetHashCode
andEquals
methods for that to work, but i am having trouble finding some examples of this.Could someone please show me the best way to remove
list1
fromlist2
?Thanks again
解决方案You can probably use the Except method to do this.
var newList = list2.Except(list1).ToList();
If you want to replace list2 then just do this:
list2 = list2.Except(list1).ToList();
From MSDN:
To compare custom data types, implement the IEquatable generic interface and provide your own GetHashCode and Equals methods for the type. The default equality comparer, Default, is used to compare values of types that implement IEquatable.
这篇关于在一个删除项目的IList<>从另外的IList<>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!