Creating nested ObservableCollections with a custom object

Viewed 38

I am trying to create a tree structure using string arrays. I'm hoping to get the structure looking like this:

-UK
 --Cars
   ---SUV
     ----Range Rover
   ---Saloon
     ----Jaguar

From these arrays

string[] suv = new string[] {"UK","Cars","SUV","Range Rover"};
string[] saloon = new string[] {"UK","Cars","Saloon","Jaguar"};    

I have a ViewModel for the tree structure implementation:

public class TransportViewModel
{
        public string Name { get; set; }
        public ObservableCollection<TransportViewModel> TransportItems { get; set; }
}

The issue I have is that I don't know how to dynamically nest the items in the string array. I was trying to loop through the array elements and do something there but I don't know what to do to get the tree structure. Can anyone help please?

public static void CreateTree(string[] transportArray)
{
   foreach(var item in transportArray)
   {
      // some TransportViewModel.Add implementation here??
   } 
}
2 Answers

You will find the code below, I hope that it will help you .

    public static void CreateTree(string[] transportArray)
    {
        var root = TransportViewModels;
        foreach (var item in transportArray)
        {
            if (FindItem(item, root) == null)
            {
                root.Add(new TransportViewModel() { Name = item, TransportItems = new ObservableCollection<TransportViewModel>() });
                root = root.LastOrDefault().TransportItems;
            }
            else
                root = FindItem(item, root).TransportItems;
        }
    }

    private static TransportViewModel FindItem(string item, ObservableCollection<TransportViewModel> root)
    {
        return  root.Where(e => e.Name == item)
                    .FirstOrDefault();
    }

What you have are flattened root-to-leaf paths in those arrays and need to reconstruct the tree they were generated from.

var tree = new ObservableCollection<TransportViewModel>();

public void CreateTree(string[] transportArray)
{
   var root = tree;
   foreach(var item in transportArray)
   {
       var found = FindItem(root, item);
       if(found == null)
       {
           root.TransportItems.Add(found = new TransportViewModel());
           root = found;
       }
   }
}

TransportViewModel FindItem(ObservableCollection<TransportViewModel> tree, string item)
{
    foreach(var node in tree)
    {
        if(node.Name == item)
        {
            return node;
        }
    }
    return null;
}
Related