What is the best way to check two List lists for equality in C#

后端 未结 6 1785
误落风尘
误落风尘 2020-12-16 13:16

There are many ways to do this but I feel like I\'ve missed a function or something.

Obviously List == List will use Object.Equals() and re

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 13:56

    I put together this variation:

    private bool AreEqual(List x, List y)
    {
        // same list or both are null
        if (x == y)
        {
            return true;
        }
    
        // one is null (but not the other)
        if (x== null || y == null)
        {
            return false;
        }
    
        // count differs; they are not equal
        if (x.Count != y.Count)
        {
            return false;
        }
    
        for (int i = 0; i < x.Count; i++)
        {
            if (!x[i].Equals(y[i]))
            {
                return false;
            }
        }
        return true;
    }
    

    The nerd in me also crawled out so I did a performance test against SequenceEquals, and this one has a slight edge.

    Now, the question to ask; is this tiny, almost measurable performance gain worth adding the code to the code base and maintaining it? I very much doubt it ;o)

提交回复
热议问题