Luke
Luke

Reputation: 1258

Sort a TreeView alphabetically using linq

I'm new to LINQ so forgive me if this is a dumb question, but from what I've started to understand of LINQ makes me believe I should be able to do the following. I want to take a set of nodes in a TreeView (at any level) and sort them alphabetically related to their siblings.

I think I would be able to do the following:

//node is already selected
TreeNode parent = node.Parent;
TreeNodeCollection siblingNodes = node.Parent.Nodes;
siblingNodes = siblingNodes.OrderBy(x => x.Text);

Since TreeNodeCollection implements IEnumerable. But the compiler is telling me that

System.Windows.Forms.TreeNodeCollection does not contain a definition for OrderBy and no extension method OrderBy accepting a first argument of type System.Windows.Forms.TreeNodeCollection could be found (are you missing a using directive or an assembly reference?)

(I am using System.Linq)

So what am I misunderstanding?

Upvotes: 1

Views: 2014

Answers (2)

malkassem
malkassem

Reputation: 1957

Based on MSDN:

http://msdn.microsoft.com/en-us/library/system.linq(v=vs.100).aspx

System.Linq extension for IEnumerable does not define OrderBy. It defined OrderBy for IEnumerable<T>.

EnumerableQuery Class vs. EnumerableQuery<T> Class

Upvotes: 1

ataravati
ataravati

Reputation: 9155

Are you missing a reference to LINQ?

using System.Linq;

UPDATE:

You need to define a TreeViewNodeSorter in order to be able to sort the nodes. This post will point you in the right direction: Sorting nodes of a TreeView

Upvotes: 3

Related Questions