0

I'm pretty new to Visual C#. I have a class called Node and a List of Nodes called children. The goal is to make a Node tree. Each Node except the root Node has exactly one parent. Each Node has 0 or more children. To that effect, as part of my Node class I have a data member called children:

List<Node> children;

I am trying to add a child Node to a Node, but I only want to add it to the List if it is not already in the List. Here is what I have. The function below is a member function of the Node class:

// children is of type List<Node>
public void AddChild(Node childNode)
{
    if(!this.children.Exists(childNode))
        this.children.Add(childNode);
}

Line 3 gives me an error. I am not using Exists right. The example code I have seen has you write a boolean function that you pass to the Exists function, but those functions all have certain criteria (i.e. age > 25). My situation does not involve needing to check the data members of any . I just want to add a Node to the List , but make sure that I have no duplicates.

Do I want to use Exists and if so, do I need to write a boolean function of some kind. Thanks.

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by VernonDozier
0

Hi,
List.Exists () Method requires the Predicate. That means write your own method to search whether the Node is already Exists.

Ex

private static bool MyPredicate (Node s)
    {
//        Check Node is Existing
//            return true;
//        else
//            return false;
    }

Usage

if ( !this.children.Exists (MyPredicate) )
    this.children.Add(childNode);
0

O.K., thanks. That clears some stuff up. I'll give it a shot. I'm actually wondering now, though, whether Contains would be better than Exists for my particular situation?

if ( !this.children.Contains (childNode) )
    this.children.Add(childNode);
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.