Compare lists that are exactly the same

-2

I'm trying to implement a list comparison method that checks to see if they match.

It should return true when the two lists passed by parameter are exactly the same (number of elements, elements and ordering).

I was able to develop part of the solution:

public bool ListasIguais(ICollection<string> x, ICollection<string> y)
{
     if (x.Count != y.Count)
         return false;


     return x.Except(y).Count() == 0 ? true : false;
}

But he is not considering the order of elements, that is, {"a", "b", "c"} and {"c", "b", "a"} he considers as equal.

How do I consider the ordination? I also wanted it to be able to receive other types of collections, not just strings, that is, it accepts ICollection<int> , ICollection<double> , ICollection<string> , ICollection<byte> . Otherwise I would have to overload.

    
asked by anonymous 09.09.2018 / 02:29

1 answer

3

Use SequenceEqual() from Linq to make it as "leaner" as possible:

public bool ListasIguais(ICollection<string> x, ICollection<string> y) => x.SequenceEqual(y);

I even find it strange that using ICollection<string> may have a reason, but it seems more like something unused and unnecessary. in fact it is so simple that it does not have to create a method just for this.

Even if you were to use the question code it does not make sense to use a if or ternary operator to generate true or false , that's just what they do.     

09.09.2018 / 17:26