0

I want to make a List<List<int>> structure so that only distinct sequences of numbers can be added. For this I create an EqualityComparer this way:

public class ListEqualityComparer<TElement> : EqualityComparer<List<TElement>>
    {
        Object hashHelp1 = new Object();
        Object hashHelp2 = new Object();

        public override bool Equals(List<TElement> x, List<TElement> y)
        {
            if (x == null && y == null)
                return true;
            else if (x == null || y == null)
                return false;
            else if (x.SequenceEqual(y))
                return true;
            else
                return false;
        }

        public override int GetHashCode(List<TElement> obj)
        {
            return (hashHelp1, hashHelp2).GetHashCode();
        }
    }

so I want two lists to be considered equal, if their sequences of elements are equal.

However, if I try to create

ListEqualityComparer<List<int>> LEC = new ListEqualityComparer<List<int>>();
List<List<int>> list = new List<List<int>>(LEC);

I get an error:

Argument 1: cannot convert from 'MyNamespace.MyFolder.ListEqualityComparer<System.Collections.Generic.List<int>>' to 'System.Collections.Generic.IEnumerable<System.Collections.Generic.List<int>>'.

What does it actually mean?

On my belief the program should just replace TElement with List<int>and go, but obviously something different happens here. I am somehow confused, because I have implemented abother EqualityComparer recently, and the lines

MyStructureEqualityComparer<int, ulong> MSEC= new MyStructureEqualityComparer<int, ulong>();
HashSet<MyStructure<int, ulong>> test = new HashSet<MyStructure<int,ulong>>(MSEC);

were fine. What I am doing wrong?

jupiter_jazz
  • 333
  • 2
  • 8
  • 1
    Take a look at all the [constructors](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.-ctor) for `List`. Do you see one that takes a comparer? – madreflection Apr 16 '20 at 15:48
  • @madreflection ok, good point, thank you. If so, what should I do? How to tell a list not to add lists, if a similar sequence is already present? – jupiter_jazz Apr 16 '20 at 15:59
  • 1
    list does not have this functionality. You can create your own `UniqueList : List` that supports that, but you would essentially reproduce a bit worse HashSet. You can always create an extenstion method `AddUnique(this List, T elem, IEqualityComparer` that checks if the list contains equal element. Still, this is just worse HashSet. Why do you need a list over a HashSet? – Krzysztof Skowronek Apr 16 '20 at 16:07
  • @KrzysztofSkowronek I need to store sequences of numbers and I do not know how much sequences it can be, as well as how long each particular sequence can be. The list for numbers seems to be ok. I have chosen a list for sequences as well, but it can be a HashSet, too. In any case I need to save the sequence of numbers only once. – jupiter_jazz Apr 16 '20 at 16:29

0 Answers0