在一个删除项目的IList<>从另外的IList<> [英] Remove items in one IList<> from another IList<>

查看:115
本文介绍了在一个删除项目的IList<>从另外的IList<>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起张贴这样的基本问题,我是新来的LINQ和我试图找出这样做短暂通过每个的IList

我有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 from list2. I have been looking at the Except() method but apparently i need my ItemsDTO class to override the GetHashCode and Equals 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 from list2?

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&LT;&GT;从另外的IList&LT;&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆