Examining two string arrays for equivalence

前端 未结 5 1385
无人共我
无人共我 2021-01-21 21:38

Is there a better way to examine whether two string arrays have the same contents than this?

string[] first = new string[]{\"cat\",\"and\",\"mouse\"};
string[] s         


        
5条回答
  •  执笔经年
    2021-01-21 21:55

    Nothing wrong with the logic of the method, but the fact that you're testing Contains for each item in the first sequence means the algorithm runs in O(n^2) time in general. You can also make one or two other smaller optimisations and improvements

    I would implement such a function as follows. Define an extension method as such (example in .NET 4.0).

    public static bool SequenceEquals(this IEnumerable seq1, IEnumerable seq2)
    {
        foreach (var pair in Enumerable.Zip(seq1, seq2)
        {
            if (!pair.Item1.Equals(pair.Item2))
                return;
        }
        return false;
    }
    

提交回复
热议问题