Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create TreeNodes with key in a Linq expression

Tags:

c#

linq

treeview

I am trying to create a TreeNode with a key, but there is no constructor for TreeNode that takes a key and a text. I found only the following solutions:

TreeNode tn = new TreeNode("text node");
tn.Name = "keyNode";

 

treeView.Nodes.Add("keyNode", "text node");

But those ways do not suit me, as I am trying to add new TreeNodes to my treeView with a Linq query.


Here is what I would like to do ideally:

treeView.Nodes.AddRange(
    myListOfObject.Select(x => new TreeNode(x.somePropertyForKey, 
                                            x.somePropertyForText)).
                   ToArray<TreeNodes>());

Am I stuck to use a foreach loop to create the TreeNodes or do you see a way to do this one-line-ish?

like image 958
Otiel Avatar asked Dec 06 '25 08:12

Otiel


2 Answers

Thats what the new initialization syntax is for

TreeNode tn = new TreeNode("text node") {Name = "keynode"} ;
like image 96
rerun Avatar answered Dec 08 '25 22:12

rerun


treeView.Nodes.AddRange(myListOfObject.Select(new TreeNode
               {
                  Name = "keyNode", 
                  TreeNode = new TreeNode[]{new TreeNode{Name="text node"}}}
               });

Should be something like that. (Please check the braces and syntax)

You would want to use this constructor TreeNode(String, TreeNode[])

BTW, if that does not work and you are not hitting a database, you can do just the following:

treeView.Nodes.AddRange(myListOfObject.Select(new TreeNode
               (
                  "keyNode", 
                  new TreeNode[]{new TreeNode{Name="text node"}}}
               );
like image 21
AD.Net Avatar answered Dec 08 '25 22:12

AD.Net