-2

i have hard time to achieve some expected result with infinity loop. I want to create multi level category with some customization in result.

Source Data

   ID    |      Name      | ParentID |
---------+----------------+----------+
   1     |   Category 1   |    0     |
   2     |   Category 2   |    1     |
   3     |   Category 3   |    1     |
   4     |   Category 4   |    3     |
   5     |   Category 5   |    3     |
   6     |   Category 6   |    4     |

Result i expected in JSON

[
{"ID":1,"Name":"Category 1"},
{"ID":2,"Name":"Category 1/Category 2"},
{"ID":3,"Name":"Category 1/Category 3"},
{"ID":4,"Name":"Category 1/Category 3/Category 4"},
{"ID":5,"Name":"Category 1/Category 3/Category 5"},
{"ID":6,"Name":"Category 1/Category 3/Category 4/Category 6"}
]

How to get expected result using C#. I hope i can get any advice here.

lucky.omen
  • 15
  • 4
  • 1
    What have you tried? What was the problem with your approach? How can we help to improve your attempt? (edit that in the question or do more research) – Tatranskymedved Dec 15 '20 at 11:13

1 Answers1

0

Use a recursive algorithm :

    class Program
    {
        static DataTable dt = new DataTable();
        static List<string> results = new List<string>();
 
        static void Main(string[] args)
        {
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("ParentID", typeof(int));

            dt.Rows.Add(new object[] { 1, "Category 1", 0});
            dt.Rows.Add(new object[] { 2, "Category 2", 1});
            dt.Rows.Add(new object[] { 3, "Category 3", 1});
            dt.Rows.Add(new object[] { 4, "Category 4", 3});
            dt.Rows.Add(new object[] { 5, "Category 5", 3});
            dt.Rows.Add(new object[] { 6, "Category 6", 4});

            PrintRecursive(0, "");
            foreach (string result in results)
            {
                Console.WriteLine(result);
            }
            Console.ReadLine();

        }
        static void PrintRecursive(int parent, string name)
        {
            DataRow[] rows = dt.AsEnumerable().Where(x => x.Field<int>("ParentID") == parent).ToArray();
            if (rows.Length != 0)
            {
                foreach (DataRow row in rows)
                {
                    int child = row.Field<int>("ID");
                    string childStr = row.Field<string>("Name");
                    results.Add(string.Format("\"ID\":{0},\"Name\":\"{1}\"", child, name));
                    PrintRecursive(child, name + "/" + childStr);
                }
            }
        }
    }
 
jdweng
  • 33,250
  • 2
  • 15
  • 20