LINQ:确定两个序列是否包含完全相同的元素 [英] LINQ: Determine if two sequences contains exactly the same elements

查看:71
本文介绍了LINQ:确定两个序列是否包含完全相同的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定两组是否包含完全相同的元素.顺序无关紧要.

I need to determine whether or not two sets contains exactly the same elements. The ordering does not matter.

例如,应将这两个数组视为相等:

For instance, these two arrays should be considered equal:

IEnumerable<int> data = new []{3, 5, 6, 9};
IEnumerable<int> otherData = new []{6, 5, 9, 3}

一个集合不能包含任何不在另一个集合中的元素.

One set cannot contain any elements, that are not in the other.

可以使用内置查询运算符来完成此操作吗?考虑到元素的数量可能从几到几百个,实现它的最有效方法是什么?

Can this be done using the built-in query operators? And what would be the most efficient way to implement it, considering that the number of elements could range from a few to hundreds?

推荐答案

如果要将数组视为集合",而忽略顺序和重复项,则可以使用

If you want to treat the arrays as "sets" and ignore order and duplicate items, you can use HashSet<T>.SetEquals method:

var isEqual = new HashSet<int>(first).SetEquals(second);

否则,您最好的选择可能是以相同的方式对两个序列进行排序,然后使用SequenceEqual进行比较.

Otherwise, your best bet is probably sorting both sequences in the same way and using SequenceEqual to compare them.

这篇关于LINQ:确定两个序列是否包含完全相同的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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