Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to convert List<Object> to ObservableCollection<Object>

Tags:

c#

.net

wpf

I have got List<Object> where the Object has a lot of childs List<Object> around 4-6 levels.

Now I have to bind it to WPF TreeView... :(

Which the best way to convert it into ObservableCollection<Object> is?

like image 577
Terminador Avatar asked Jan 30 '12 19:01

Terminador


3 Answers

Assuming you mean ObservableCollection<T>, if you wanted the List directly to the ObservableCollection as-is, just use the constructor:

var oc = new ObservableCollection<Object>(yourListOfObject);

Now, if you're wanting to unwind each of those, you would need to do some work to collapse them into a single ObservableCollection<T>.

like image 136
James Michael Hare Avatar answered Oct 08 '22 03:10

James Michael Hare


One part of the answer is to use Reactive Extensions (Rx). You can get it from NuGet and it's developed by Microsoft. With the help of it you can simply say: myListCollection.ToObservable();

If your child collections always are in a node with the same name you could use a while(item.Collection != null || item.Collection.Count == 0) and put the ToObservable() within the loop

like image 30
Mharlin Avatar answered Oct 08 '22 04:10

Mharlin


Assuming you have a node class defined like so:

public class Node
{
    public ICollection<Node> Children { get; set; }
}

You can use recursion to convert List<Node> collections, at any level of depth:

public static ObservableCollection<Node> ToObservableRecursive(ICollection<Node> nodes)
{
    foreach (Node node in nodes)
        if (node.Children != null)
            node.Children = ToObservableRecursive(node.Children);

    return new ObservableCollection<Node>(nodes);
}
like image 3
Douglas Avatar answered Oct 08 '22 02:10

Douglas