I have a database table like shown below:
MenuItemID | int [Primary Key] 1 -----+
MenuItemName | nvarchar(100) |
ParentID | int * -----+
As you can see in the above schematic diagram, ParentID column refers to MenuItemID due to which we can obtain hierarchical outpu.
The sample data in above table is as shown below:
From the sample data above, I want the output like:
Electronics
Mobile
Desktop
Laptop
Lenovo
Dell
Sports
Cricket
Football
Hockey
Stationary
Books
Pens
Pencils
Erasers
What I have tried:
I have tried the below mentioned code, where I tried to use GroupJoin extension method to achieve the required output:
class Program
{
static void Main(string[] args)
{
OnlineShoppingEntities db = new OnlineShoppingEntities();
var x = db.MenuItems.GroupJoin(db.MenuItems,
m => m.MenuItemID,
m => m.ParentID,
(parentMenuItems, childMenuItems) => new
{
ParentMenuItems = parentMenuItems,
ChildMenuItems = childMenuItems
});
foreach (var v in x)
{
Console.WriteLine(v.ParentMenuItems.MenuItemName);
foreach (var m in v.ChildMenuItems)
{
Console.WriteLine("\t" + m.MenuItemName);
}
}
}
}
The output I got:
I am very much surprised with the output, as I expected the required output as mentioned above.