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,
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>
)
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>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With