Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query a TreeNodeCollection

Tags:

c#

linq

winforms

I have a treeview control on a windows form UI and it has a few nodes (with multiple child nodes). I want to query the nodes collection so as to, say, 1. select those whose name start with 'x'
2. select those which do not have any data in Node.Tag field.

Can someone please suggest me a way to do this. Linq would make it easy and neat, but I found nothing much on Linq to query TreeNodeCollection.

Thanks,

like image 959
ViV Avatar asked Apr 13 '12 11:04

ViV


2 Answers

Because TreeNodeCollection pre-dates .NET 2.0, it isn't a generic collection, so it doesn't implement IEnumerable<T>, which is the 'master' type for LINQ goodness.

However, you can just call .Cast<TreeNode>() on a TreeNodeCollection, and you get an IEnumerable<TreeNode>, which you can then do all the LINQy goodness to.

(this approach works for any such collection that implements IEnumerable but not IEnumerable<T>)

like image 111
AakashM Avatar answered Sep 23 '22 13:09

AakashM


You may try something like this with a Fixpoint operator allowing recursive lambdas

// Fix point operator
public static Func<T, T> Fix<T>(Func<Func<T, T>, Func<T, T>> f)
{
    return t => f(Fix<T>(f))(t);
}

then

// your treeView
var tv = new TreeView();

// Your filter Func
Func<TreeNode, bool> filterStartWithXorNoData =
    node => node.Text.StartsWith("x") || string.IsNullOrEmpty(node.Text);

// Your recursive lambda
var filteredNodes = Fix<IEnumerable<TreeNode>>(
    f =>
    nodeList =>
    nodeList.SelectMany(node => f(node.ChildNodes.Cast<TreeNode>()))
      .Union(nodeList.Where(filterStartWithXorNoData)))
      (tv.Nodes.Cast<TreeNode>());
like image 26
jbl Avatar answered Sep 23 '22 13:09

jbl