How to quickly wrap a single item into a collection

The situation

I just started to play with WPF and I like that very much. Its a lot easier to do many things that were very hard to do in Win Forms.

I’m working on a software that need a tree view. In win form you have to build the entire tree a node at a time, adding them recursively until done. In WPF though, there is a faster way to do that.

First let say we have a tree structure like this:

Later in your code you define a property of that type to bind to:

With this code you can build a structured tree of nodes. Then you can use a TreeView object in your xaml file:

The Problem

The problem with this is that the TreeView needs a collection or at least an enumerable source as its ItemSource. What if we don’t want to bind to the Children property of the root? What if we have some interesting property to show on the root node?

The Solution

We can build a temporary collection to pleased the TreeView:

Of course this will work. But isn’t a little too much having to create an instance of a list object to do that? Here is a simpler an more efficient way to achieve the same result.

Wow! That’s short! If you don’t know what “yield return” keyword is, you may find this code sample a little odd. “yield return” is what LINQ uses internally to iterate thru any IEnumerable data source without having to build an internal list. In our case we only need a list of one item, so using this technique can optimise your code.


One thought on “How to quickly wrap a single item into a collection

Leave a Reply