简体   繁体   English

在C#中比较2个整数列表/数组的最佳方法是什么?

[英]What is the best way to compare 2 integer lists / array in C#

I want to compare 2 integer list for equality. 我想比较2个整数列表是否相等。 I am happy to sort them in advance if that makes it easier. 如果能让它变得更容易,我很乐意提前对它们进行排序。 Here is an example of two things that i want to compare. 这是我要比较的两件事的例子。 For the below, i want the result to be true. 对于下面,我希望结果是真的。

NOTE: there will never be any duplicates in the list (no repeating values) 注意:列表中永远不会有任何重复项(没有重复值)

 List<int> list = new List<int>(){1, 4,6,7};
 int[] myArray = new int[]{1, 6,7 ,4};

What does equality mean to you when comparing lists? 比较列表时,平等对你意味着什么? Do you care that the lists are exactly the same .... the same items in the same order? 你是否关心列表完全相同....相同的订单中的相同项目? Or just contain the same set of values, regardless of order. 或者只是包含相同的值集,无论顺序如何。

If you actually want to verify that the lists contain the same sequence of values in the same order, you can use the SequenceEqual() method in LINQ: 如果您确实想要验证列表是否以相同的顺序包含相同的值序列,则可以在LINQ中使用SequenceEqual()方法:

bool areEqual = listA.SequenceEqual( listB );

If the lists are not in the same order, you can first sort them: 如果列表的顺序不同,您可以先对它们进行排序:

bool areEqual = listA.OrderBy(x=>x).SequenceEqual( listB.OrderBy(x=>x) );

If the lists can contain duplicates, and the duplicates don't matter (with respect to equality), you can use set comparison: 如果列表可以包含重复项,并且重复项无关紧要(关于相等性),则可以使用set comparison:

bool setEqual = new HashSet<int>( listA ).SetEquals( listB );

If duplicates don't matter and you're interested in avoiding the expense of the comparison (ordering, building a hashset, etc), you could first just compare the sizes of the two collections, and only compare if they are the same. 如果重复无关紧要并且您有兴趣避免比较的费用(排序,构建哈希集等),您可以先比较两个集合的大小,并仅比较它们是否相同。

It looks like you want to compare them as sets ... in which case: 看起来你想将它们作为集合进行比较......在这种情况下:

HashSet<int> hashSet = new HashSet<int>(list);
if (hashSet.SetEquals(myArray))
{
    ...
}

Note that this will deem { 1, 2, 2, 3 } and { 1, 3, 2, 3, 1 } as being equal. 注意,这将使{1,2,2,3}和{1,3,2,3,1}相等。 Is that what you want? 那是你要的吗?

There's almost certainly something built in which will do what you want, but you'll need to be exact in your description :) 几乎可以肯定的是,内置的东西会做你想要的,但你需要在你的描述中完全准确:)

EDIT: As you've stated there will be no repeated elements, this should be fine. 编辑:正如你所说,没有重复的元素,这应该没问题。 It may be wise to document the assumption though. 然而,记录这个假设可能是明智之举。

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

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