Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Nested List from a Flat List in C#

Tags:

c#

.net

I currently have the following classes:

public class NavigationItem
{
    public int ID { get; set; }
    public string Title { get; set; }
    public int ParentID { get; set; }
    public List<NavigationItem> Children { get; set; }
}

public class FlatItem
{
    public int ID { get; set; }
    public string Title { get; set; }
    public int ParentID { get; set; }
}

I have a sample data as follows:

+====+============+==========+
| ID |   Title    | ParentID |
+====+============+==========+
|  1 | Google     |          |
+----+------------+----------+
|  2 | Microsoft  |          |
+----+------------+----------+
|  3 | Oracle     |          |
+----+------------+----------+
|  4 | Gmail      |        1 |
+----+------------+----------+
|  5 | Sheets     |        1 |
+----+------------+----------+
|  6 | Adsense    |        1 |
+----+------------+----------+
|  7 | Azure      |        2 |
+----+------------+----------+
|  8 | SharePoint |        2 |
+----+------------+----------+
|  9 | Office     |        2 |
+----+------------+----------+
| 10 | Java       |        3 |
+----+------------+----------+
| 11 | Word       |        9 |
+----+------------+----------+
| 12 | Excel      |        9 |
+----+------------+----------+
| 13 | PowerPoint |        9 |
+----+------------+----------+

I already have the code to pull all the information from the sample data above and turn it into a List<FlatItem> object.

What's the best approach so that I can have a List<NavigationItem> object which will look like something below:

  • Google
    • Gmail
    • Sheets
    • AdSense
  • Microsoft
    • Azure
    • SharePoint
    • Office
      • Word
      • Excel
      • PowerPoint
  • Oracle
    • Java

I'm thinking of creating a recursive method to loop through my List<FlatItem> then structure it in a way to be a nested list of NavigationItem.

like image 352
lem.mallari Avatar asked Jun 05 '18 10:06

lem.mallari


People also ask

How do you make a list of lists flat listed?

Flattening a list of lists entails converting a 2D list into a 1D list by un-nesting each list item stored in the list of lists - i.e., converting [[1, 2, 3], [4, 5, 6], [7, 8, 9]] into [1, 2, 3, 4, 5, 6, 7, 8, 9] .

How can we create nested lists?

First, we'll create a nested list by putting an empty list inside of another list. Then, we'll create another nested list by putting two non-empty lists inside a list, separated by a comma as we would with regular list elements.

What are nested lists give any example of nested list?

A nested list is a list that appears as an element in another list. In this list, the element with index 3 is a nested list. If we print( nested[3] ), we get [10, 20] .

How to create nested list in R with example?

Create Nested List in R (2 Examples) 1 Introducing Exemplifying Data. As you can see based on the previously shown output of the RStudio console, we have created three list objects in R. 2 Example 1: Create List of Lists Using list () Function. ... 3 Example 2: Create List of Lists in for-Loop. ... 4 Video, Further Resources & Summary. ...

What is a nested list in C++?

Nested lists are like jagged or 2D lists. List, nested. A List can have elements of List type. This is a jagged list, similar in syntax to a jagged array. Lists are not by default multidimensional in C#.

How to access a specific element within a nested list in Java?

Part 1 We create a list, and add sub-lists to it. The first List will contain an internal array of List references. Part 2 This method receives a parameter of type List<List<int>>. It uses for each to loop over the inner contents of each List. Part 3 We can access a specific element within a nested list.

How to convert a nested list to a single List in Python?

The task is to convert a nested list into a single list in python i.e no matter how many levels of nesting is there in python list, all the nested has to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside.


2 Answers

No need for recursion. You could use LINQ to build the structure easily:

List<FlatItem> flatItems = ...;

var navigationItems = flatItems.Select(
    i => new NavigationItem { ID = i.ID, Title = i.Title, ParentID = i.ParentID }
).ToList();

foreach (var i in navigationItems)
    i.Children = navigationItems.Where(n => n.ParentID == i.ID).ToList();

// get Google, Microsoft, Oracle items
var rootNavigationItems = navigationItems.Where(n => n.ParentID == 0);
like image 183
ViRuSTriNiTy Avatar answered Oct 15 '22 11:10

ViRuSTriNiTy


Try this:

List<FlatItem> source = new List<UserQuery.FlatItem>()
{
    new FlatItem() { ID = 1, Title = "Google", ParentID = null },
    new FlatItem() { ID = 2, Title = "Microsoft", ParentID = null },
    new FlatItem() { ID = 3, Title = "Oracle", ParentID = null },
    new FlatItem() { ID = 4, Title = "Gmail", ParentID = 1 },
    new FlatItem() { ID = 5, Title = "Sheets", ParentID = 1 },
    new FlatItem() { ID = 6, Title = "Adsense", ParentID = 1 },
    new FlatItem() { ID = 7, Title = "Azure", ParentID = 2 },
    new FlatItem() { ID = 8, Title = "SharePoint", ParentID = 2 },
    new FlatItem() { ID = 9, Title = "Office", ParentID = 2 },
    new FlatItem() { ID = 10, Title = "Java", ParentID = 3 },
    new FlatItem() { ID = 11, Title = "Word", ParentID = 9 },
    new FlatItem() { ID = 12, Title = "Excel", ParentID = 9 },
    new FlatItem() { ID = 13, Title = "PowerPoint", ParentID = 9 },
};

var lookup = source.ToLookup(x => x.ParentID);

Func<int?, List<NavigationItem>> build = null;
build = pid =>
    lookup[pid]
        .Select(x => new NavigationItem()
        {
            ID = x.ID,
            Title = x.Title,
            ParentID = x.ParentID,
            Children = build(x.ID)
        })
        .ToList();

To start the process call build(null). That gives me this:

Tree

This does assume that the ParentId property is a int? - which your data table does suggest.

like image 45
Enigmativity Avatar answered Oct 15 '22 12:10

Enigmativity