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

后端 未结 6 1399
一整个雨季
一整个雨季 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:49

    If you aren't concerned about duplicates, or you're concerned about duplicates but not overly concerned about performance micro-optimisations, then the various techniques in Jon's answer are definitely the way to go.

    If you're concerned about duplicates and performance then something like this extension method should do the trick, although it really doesn't meet your "shortest code" criteria!

    bool hasSameElements = A.HasSameElements(B);
    
    // ...
    
    public static bool HasSameElements(this IList a, IList b)
    {
        if (a == b) return true;
    
        if ((a == null) || (b == null)) return false;
    
        if (a.Count != b.Count) return false;
    
        var dict = new Dictionary(a.Count);
        foreach (string s in a)
        {
            int count;
            dict.TryGetValue(s, out count);
            dict[s] = count + 1;
        }
    
        foreach (string s in b)
        {
            int count;
            dict.TryGetValue(s, out count);
    
            if (count < 1) return false;
    
            dict[s] = count - 1;
        }
    
        return dict.All(kvp => kvp.Value == 0);
    }
    

    (Note that this method will return true if both sequences are null. If that's not the desired behaviour then it's easy enough to add in the extra null checks.)

提交回复
热议问题