开发者

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

开发者 https://www.devze.com 2023-02-28 02:27 出处:网络
I want to compare 2 integer list for equality. 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

I want to compare 2 integer list for equality. 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};
 in开发者_如何学编程t[] 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:

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:

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. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号