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

后端 未结 6 1398
一整个雨季
一整个雨季 2021-02-06 12:18

There are two lists of string

List A;
List B;

What is the shortest code you would suggest to check that A.Count ==

6条回答
  •  盖世英雄少女心
    2021-02-06 12:37

    If you don't need to worry about duplicates:

    bool equal = new HashSet(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(A).SetEquals(B);
    

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

提交回复
热议问题