简体   繁体   English

比较两个清单<Objects>

[英]Compare Two List<Objects>

What is the best route to compare 2 List<MyClasses> ? 比较2 List<MyClasses>的最佳途径是什么?

List 2 could contain more values than List 1 which is ok. 列表2可以包含比列表1更好的值。 Just need to make sure List 2 contains everything in List 1. They also won't be in the same order. 只需确保列表2包含列表1中的所有内容。它们的顺序也不相同。

您可以使用“ Except来查找两个集合的集合差异。

var hasAllItems = !list2.Except(list1).Any();

This will let you know if list2 does not contain an item that is in list1: 这将让您知道list2是否不包含list1中的项目:

list1.Any(x => !list2.Contains(x));

You could put it in a variable so you don't have to think about the double negatives: 您可以将其放在变量中,这样就不必考虑双重否定:

var list2ContainsList1 = !list1.Any(x => !list2.Contains(x));

One way to do it: 一种方法:

List1.All(o => List2.Contains(o));

This says "return true if and only if every item in list 1 is contained in list 2" 这表示“当且仅当列表1中的每个项目都包含在列表2中时,才返回true”

The simplest approach is to use Except (in your case, you don't care about the order of your elements in the lists): 最简单的方法是使用Except (在您的情况下,您不必关心列表中元素的顺序):

var elementsInList2NotInList1 = list2.Except(list1);

Remember that this method uses a default equality comparer to compare the values. 请记住,此方法使用默认的相等比较器比较值。 If you do care about the ordering of the elements, you'll need to do extra work, in order to check how each element of a list is equal to an element of the other list. 如果您确实关心元素的顺序,则需要做一些额外的工作,以便检查列表中的每个元素与另一个列表中的元素如何相等。 The extra work would be the following: 额外的工作如下:

  1. Create your own comparer, implementing the interface IEqualityComparer ; 创建自己的比较器,实现IEqualityComparer接口;
  2. Create your own Equals() and GetHashCode() methods for your custom data type. 为您的自定义数据类型创建自己的Equals()GetHashCode()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM