Compare lists that are exactly the same

Asked

Viewed 385 times

-2

I’m trying to implement a list comparison method that checks if they are equal.

It must return true when the two lists passed by parameter are exactly equal (number of elements, elements and sorting).

I managed 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 the elements, ie, {"a", "b", "c"} and {"c", "b", "a"} he regards as equal.

How do I get him to consider ordination? I also wanted him to be able to receive other types of collections and not just strings, that is, to accept ICollection<int>, ICollection<double>, ICollection<string>, ICollection<byte>. Otherwise I’d have to overload.

1 answer

4


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

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

I put in the Github for future reference.

I even find the use of ICollection<string>, may even have a motive, but it looks more like something used for no reason and an unnecessary limiter. It’s actually so simple that you don’t even have to create a method just for this.

Even if I was going to use the question code, it doesn’t make sense to use a if or ternary operator to generate true or false, that’s just what they do.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.