Dumbo
Dumbo

Reputation: 14142

How to clean up "TreeNode"s with same Text property in a TreeView?

I have a TreeView which will be populated with some Nodes. The problem is, this nodes can have different Tag and Name property but some of them can have the same Text property.

I want to have only one node from each of above nodes, so the TreeView will have unique nodes by Text.

I am trying to make a list of all nodes then filter them, then add the new List to the TreeView. Here is my approach, and I commented the line which does not compile.

        //Remove Duplicated Nodes
        List<TreeNode> oldPinGrpNodes = new List<TreeNode>();
        List<TreeNode> newPinGrpNodes = new List<TreeNode>();
        TreeNode tempNode;


        foreach (TreeNode node in tvPinGroups.Nodes)
        {
            oldPinGrpNodes.Add(node);
        }

        foreach (TreeNode node in oldPinGrpNodes)
        {
            if (newPinGrpNodes.Contains(node.Text)) continue; //this does not compile!
            //How to do a check in the IF statement above?

            //Continue with adding the unique pins to the newList
        }

Or if you have any better idea please let me know!

Upvotes: 2

Views: 1205

Answers (4)

Ivan Bianko
Ivan Bianko

Reputation: 1769

Try this. I'm using ToLookup extension method in System.Linq:

//Remove Duplicated Nodes
      List<TreeNode> oldPinGrpNodes = new List<TreeNode>();
      Dictionary<string, TreeNode> newPinGrpNodes = new Dictionary<string, TreeNode>();
      TreeNode tempNode;


      foreach (TreeNode node in tvPinGroups.Nodes)
      {
        oldPinGrpNodes.Add(node);
      }

      foreach (TreeNode node in oldPinGrpNodes)
      {
        if (newPinGrpNodes.ContainsKey(node.Text)) continue; //this does not compile!
        //How to do a check in the IF statement above?

        //Continue with adding the unique pins to the newList

        // do something like
        newPinGrpNodes.Add(node.Text, node);
      }

As for your compilation error, newPinGrpNodes - collection of type TreeNode and you try to search string there.

UPDATE: For performance, it's better to use Dictionary for searching items: Dictionary<string, TreeNode> instead of List<TreeNode>.

Upvotes: 1

ratneshsinghparihar
ratneshsinghparihar

Reputation: 301

    foreach (TreeNode node in oldPinGrpNodes)      
 {        
 if ( from m in  newPinGrpNodesLookup  where m.text=node.Text select m).first ==null)
  continue; 
 } 

Upvotes: 1

Kamyar
Kamyar

Reputation: 18797

have you tried the following Linq query, instead of your check?

if (newPinGrpNodes.Any(n => n.Text == node.Text)) continue;

Upvotes: 2

L.B
L.B

Reputation: 116178

if(newPinGrpNodes.Any(n => n.Text==node.Text)) continue;

Upvotes: 1

Related Questions