Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: how do you check lists are the same size & same elements?

There are two lists of string

List<string> A;
List<string> B;

What is the shortest code you would suggest to check that A.Count == B.Count and each element of A in B and vise versa: every B is in A (A items and B items may have different order).

like image 605
Andrew Florko Avatar asked Nov 24 '10 12:11

Andrew Florko


2 Answers

If you don't need to worry about duplicates:

bool equal = new HashSet<string>(A).SetEquals(B);

If you are concerned about duplicates, that becomes slightly more awkward. This will work, but it's relatively slow:

bool equal = A.OrderBy(x => x).SequenceEquals(B.OrderBy(x => x));

Of course you can make both options more efficient by checking the count first, which is a simple expression. For example:

bool equal = (A.Count == B.Count) && new HashSet<string>(A).SetEquals(B);

... but you asked for the shortest code :)

like image 79
Jon Skeet Avatar answered Sep 23 '22 23:09

Jon Skeet


A.Count == B.Count && new HashSet<string>(A).SetEquals(B);

If different frequencies of duplicates are an issue, check out this question.

like image 28
Ani Avatar answered Sep 22 '22 23:09

Ani