Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting result of data table into tree using C#

I have a dataset which contains 4 columns. Name, key, parentKey, Level. I need to convert this DataTable into a tree structure. I am attaching an image which will give you some idea what I want to do. What is the most efficient way to convert the DataTable into an object which I can use to generate a tree structure. Please help.

Please Note: Data can come in any order in DataTable. Is it possible to sort the dataTable on first Level column and then on parentKey column? I think, If I can do that, it would be easy to convert the output into tree structure.

enter image description here

I have added a class which mimic the dataset & I have sorted the data within the datatable.

namespace SortDataTable
{


    public class Program
    {
        private static void Main(string[] args)
        {
            DataTable table = new DataTable();
            table.Columns.Add("Name", typeof (string));
            table.Columns.Add("Key", typeof (string));
            table.Columns.Add("ParentKey", typeof (string));
            table.Columns.Add("Level", typeof (int));


            table.Rows.Add("A", "A1", null, 1);
            table.Rows.Add("B", "A2", "A1", 2);
            table.Rows.Add("C", "A3", "A1", 2);
            table.Rows.Add("D", "A4", "A1", 2);

            table.Rows.Add("E", "A5", "A2", 3);
            table.Rows.Add("F", "A6", "A5", 4);
            table.Rows.Add("G", "A7", "A3", 3);
            table.Rows.Add("H", "A8", "A4", 3);


            table.Rows.Add("I", "A9", "A4", 3);
            table.Rows.Add("J", "A10", "A4", 3);
            table.Rows.Add("K", "A11", "A10", 4);
            table.Rows.Add("L", "A12", "A10", 4);

            table.Rows.Add("M", "A13", "A12", 5);
            table.Rows.Add("N", "A14", "A12", 5);
            table.Rows.Add("O", "A15", "A10", 4);

            DataView view = table.DefaultView;

            // By default, the first column sorted ascending.
            view.Sort = "Level, ParentKey DESC";


            foreach (DataRowView row in view)
            {
                Console.WriteLine(" {0} \t {1} \t {2} \t {3}", row["Name"], row["Key"], row["ParentKey"], row["Level"]);
            }
            Console.ReadKey();

        }

    }


   public class Node<T>
    {
        internal Node() { }
        public T Item { get; internal set; }
        public int Level { get; internal set; }
        public Node<T> Parent { get; internal set; }
        public IList<Node<T>> Children { get; internal set; }



        public static IEnumerable<Node<T>> ToHierarchy<T>( IEnumerable<T> source, Func<T, bool> startWith, Func<T, T, bool> connectBy)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (startWith == null) throw new ArgumentNullException("startWith");
            if (connectBy == null) throw new ArgumentNullException("connectBy");
            return source.ToHierarchy(startWith, connectBy, null);
        }

        private static IEnumerable<Node<T>> ToHierarchy<T>(IEnumerable<T> source, Func<T, bool> startWith, Func<T, T, bool> connectBy, Node<T> parent)
        {
            int level = (parent == null ? 0 : parent.Level + 1);

            var roots = from item in source
                        where startWith(item)
                        select item;
            foreach (T value in roots)
            {
                var children = new List<Node<T>>();
                var newNode = new Node<T>
                {
                    Level = level,
                    Parent = parent,
                    Item = value,
                    Children = children.AsReadOnly()
                };

                T tmpValue = value;
                children.AddRange(source.ToHierarchy(possibleSub => connectBy(tmpValue, possibleSub), connectBy, newNode));

                yield return newNode;
            }
        }
    }





}
like image 615
SharpCoder Avatar asked Aug 13 '13 08:08

SharpCoder


1 Answers

I use the following extension method to do this kind of thing:

    public class Node<T>
    {
        internal Node() { }
        public T Item { get; internal set; }
        public int Level { get; internal set; }
        public Node<T> Parent { get; internal set; }
        public IList<Node<T>> Children { get; internal set; }
    }

    public static IEnumerable<Node<T>> ToHierarchy<T>(
        this IEnumerable<T> source,
        Func<T, bool> startWith,
        Func<T, T, bool> connectBy)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (startWith == null) throw new ArgumentNullException("startWith");
        if (connectBy == null) throw new ArgumentNullException("connectBy");
        return source.ToHierarchy(startWith, connectBy, null);
    }

    private static IEnumerable<Node<T>> ToHierarchy<T>(
        this IEnumerable<T> source,
        Func<T, bool> startWith,
        Func<T, T, bool> connectBy,
        Node<T> parent)
    {
        int level = (parent == null ? 0 : parent.Level + 1);

        var roots = from item in source
                    where startWith(item)
                    select item;
        foreach (T value in roots)
        {
            var children = new List<Node<T>>();
            var newNode = new Node<T>
            {
                Level = level,
                Parent = parent,
                Item = value,
                Children = children.AsReadOnly()
            };

            T tmpValue = value;
            children.AddRange(source.ToHierarchy(possibleSub => connectBy(tmpValue, possibleSub), connectBy, newNode));

            yield return newNode;
        }
    }

In the case of a DataTable as the source, you can use it like this:

var hierarchy =
    sourceTable.AsEnumerable()
               .ToHierarchy(row => row.IsNull("ParentKey"),
                            (parent, child) => parent.Field<int>("Key") ==
                                               child.Field<int>("ParentKey"))

(hierarchy is an IEnumerable<Node<DataRow>>)

Note that if you define the parent-child relation in the DataTable itself, you already have a tree structure... you just need to select the roots (items with no parent).

like image 124
Thomas Levesque Avatar answered Oct 28 '22 11:10

Thomas Levesque