Dot Net For All

Create Hierarchical data using C# LINQ

Hello friends, In this article I will show you how to create hierarchical or parent child relation ship data using C# LINQ query. This is a very concise code made simpler with the use of LINQ in C#. I am considering that we have data coming from first table which contains a foreign key reference to other DataTable.

Creating raw DataTable for Code Example

In this code example, I have created two DataTable as sample data. Otherwise this data would be coming from some data source. And data will already be present in the DataTable.

DataTable dtStudents = new DataTable();
dtStudents.Columns.Add("ID", typeof(int));
dtStudents.Columns.Add("FirstName", typeof(String));
dtStudents.Columns.Add("LastName", typeof(String));
dtStudents.Columns.Add("Marks", typeof(int));
dtStudents.Columns.Add("StandardID", typeof(int));
string[] fName = { "Vikram", "Martin", "Tim", "Cook", "Larry" };
string[] lName = { "Chaudhary", "George", "Jobs", "Steve", "Page" };
Random random = new Random();

for (int i = 0; i < 5; i++)
{
    DataRow dtRow = dtStudents.NewRow();

    dtRow["ID"] = i + 1;
    dtRow["FirstName"] = fName[i];
    dtRow["LastName"] = lName[i];
    dtRow["Marks"] = random.Next(400, 500);
    dtRow["StandardID"] = random.Next(1, 3);

    dtStudents.Rows.Add(dtRow);
}

DataTable dtStandard = new DataTable();            
dtStandard.Columns.Add("StandardID", typeof(int));
dtStandard.Columns.Add("Name", typeof(String));
string[] sSname = { "First", "Second", "Third" };


for (int i = 1; i <= 3; i++)
{
    DataRow dtRow = dtStandard.NewRow();
    dtRow["StandardID"] = i;
    dtRow["Name"] = sSname[i - 1];
    dtStandard.Rows.Add(dtRow);
}

The code is quite self explanatory. There are two tables. First is Student table. It contains many students with their Standard or class.

And the second table is the lookup table for Standard.

Hierarchical data using C# LINQ

Here comes the next part and important part of the article. I have to create hierarchical or tree view or parent – child relationship out of these two DataTables.

Below is the C# LINQ Lambda query to achieve the same.

var query = dtStandard.AsEnumerable().Select(row => new {
    Standard = row["Name"],
    Students = dtStudents.Select("StandardID=" + row["StandardID"]).
                            Select(item1 =>
                            new
                            {
                                Name = string.Format("{0}, {1}", item1["firstName"], item1["lastName"]),
                                Marks = item1["Marks"]
                            })
}).ToList();

I have used the nested query to achieve the same. First I am querying the Standard Table, and inside the same LINQ query I am again querying the Student DataTable to find the students of a particular class.

Have a look at the below figure for visual representation of data.

Finally below is the code to traverse the hierarchical data.

foreach (var standard in query)
{
    Console.WriteLine(String.Format("{0}", standard.Standard));
    foreach (var student in standard.Students)
    {
        Console.WriteLine(String.Format("\t Student Name: {0}, Marks: {1}", student.Name, student.Marks));
    }
}

Though I have used two DataTables as the data source, but same can be achieved with other data source. Like two custom class collections.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview