比较两个列表< T>平等的对象,忽略秩序 [英] Compare two List<T> objects for equality, ignoring order

查看:126
本文介绍了比较两个列表< T>平等的对象,忽略秩序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个列表比较问题。

List<MyType> list1;
List<MyType> list2;



我需要检查他们都有相同的元素,不管他们在列表中的位置。每个 MyType 对象可能在列表中多次出现。是否有内置函数检查这个?如果我保证每个元素在列表中只出现一次,该怎么办?

I need to check that they both have the same elements, regardless of their position within the list. Each MyType object may appear multiple times on a list. Is there a built-in function that checks this? What if I guarantee that each element appears only once in a list?

编辑:感谢您的答案,但我忘了添加一些东西,每个元素的出现次数应该在两个列表上相同。

Guys thanks for the answers but I forgot to add something, the number of occurrences of each element should be the same on both lists.

推荐答案

如果你希望他们真的相等相同的项目和每个项目的相同数量),我认为最简单的解决方案是在比较之前排序:

If you want them to be really equal (i.e. the same items and the same number of each item), I think that the simplest solution is to sort before comparing:

Enumerable.SequenceEqual(list1.OrderBy(t => t), list2.OrderBy(t => t))



编辑:



这里是一个执行得更好一点(大约十倍)的解决方案,只需要 IEquatable ,而不是 IComparable

public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2) {
  var cnt = new Dictionary<T, int>();
  foreach (T s in list1) {
    if (cnt.ContainsKey(s)) {
      cnt[s]++;
    } else {
      cnt.Add(s, 1);
    }
  }
  foreach (T s in list2) {
    if (cnt.ContainsKey(s)) {
      cnt[s]--;
    } else {
      return false;
    }
  }
  return cnt.Values.All(c => c == 0);
}



编辑2:



要处理任何数据类型作为键(例如可空类型,如Frank Tzanabetis指出),你可以做一个版本,需要一个比较器

public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2, IEqualityComparer<T> comparer) {
  var cnt = new Dictionary<T, int>(comparer);
  ...

这篇关于比较两个列表&lt; T&gt;平等的对象,忽略秩序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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