0

I have a list of type List<TreeNode<DepFile>>. I need to check if this list has a TreeNode<DepFile> previosuly added. I use IndexOf for that purpose. I implement the Equals method on DepFile type.

This does not work.

The question is: How can I tell the list that it uses the Equals method implementented in DepFile data type?

Taking my data type:

class DepFile: IEqualityComparer<DepFile>
{
    public string coddep { get; set; }
    public int codtipodep { get; set; }

    public bool Equals(DepFile x, DepFile y)
    {
        return x.coddep == y.coddep
            && x.codtipodep == y.codtipodep;
    }
}

I build a litte Tree structure of T. The AddChild method has to check if element is already in the list and insert or not in the list. The DepFile or other data that implements IEqualitComparer is stored in Value field.

class TreeNode<T>
{

    public List<TreeNode<T>> Children { get;set; }
    public T Value { get; set; } // It stores the data itself

    public TreeNode()
    {
        Children = new List<TreeNode<T>>();
    }

    public TreeNode<T> AddChild(TreeNode<T> data)
    {
        TreeNode<T> node = data;
        int index = Children.IndexOf(data);// Which Equals use this IndexOf ????
        if (index != -1)
        {
            node = Children.ElementAt(index);
        }
        else
        {
            data.Parent = this;
            Children.Add(data);
        }
        return node;
    }
}
anmarti
  • 5,045
  • 10
  • 55
  • 96
  • 1
    `IEquatable`, see [duplicate](http://stackoverflow.com/questions/18003883/how-does-listt-indexof-perform-comparisons-on-custom-objects). – CodeCaster Nov 26 '15 at 10:14
  • 1
    ... or/and simply override `Equals(object)` and `GetHashCode`. `IEqualityComparer` is nice if you use LINQ methods since most have an overload that accept an `IEqualityComparer`. You don't need to change the type itself and you can have different comparers if you want. – Tim Schmelter Nov 26 '15 at 10:17

0 Answers0