C# – Query a TreeNodeCollection

c++linqwinforms

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,

Best Solution

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>)

Related Question