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)

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.

Recommended Answers

All 2 Replies

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


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


if ( !this.children.Exists (MyPredicate) )

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) )
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.