Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

integer

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};
 int[] myArray = new int[]{1, 6,7 ,4};
like image 402
leora Avatar asked Apr 23 '11 20:04

leora


Video Answer


2 Answers

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.

like image 55
LBushkin Avatar answered Nov 15 '22 16:11

LBushkin


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.

like image 37
Jon Skeet Avatar answered Nov 15 '22 16:11

Jon Skeet