1

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?

ataravati
  • 8,891
  • 9
  • 57
  • 89
Luke
  • 1,218
  • 1
  • 24
  • 40

2 Answers2

3

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

Community
  • 1
  • 1
ataravati
  • 8,891
  • 9
  • 57
  • 89
  • No, I am using System.Linq (Which was in my original question but another user edited that sentence out...) – Luke Nov 29 '13 at 20:52
  • But, that's exactly what the compiler is telling you. – ataravati Nov 29 '13 at 20:53
  • No, the other extension methods from Linq show up in intellisense, so Linq is there. I can comment out my code and create a dummy array and do a Linq OrderBy operation on that. It just doesn't like OrderBy in this TreeNodeCollection case. – Luke Nov 29 '13 at 20:54
1

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

malkassem
  • 1,937
  • 1
  • 20
  • 39
  • So is the short of that that I can't do a Linq order on a TreeNodeCollection? – Luke Nov 29 '13 at 21:59
  • You cannot directly do a Linq on a TreeNodeCollection. You can change it to List or IEnumerable and then do linq. – malkassem Dec 02 '13 at 14:23