Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a tree with LINQ expression

I have a C# List of following fields which are returned by a stored procedure:

CarrierId   ParentCarrierId Name Descrition
1            NULL            A         AA
2              1             B         BB
3              1             C         CC
4              3             D         DD
5            NULL            E         EE

I need to construct a nested object list out of this output

So each object of Carrier should have list of all it's children. Can anyone help me construct a LINQ code to accomplish this?

Desired Result:

 CarrierId = 1
      |__________________ CarrierId = 2
      |__________________ CarrierId = 3
                              |___________________ CarrierId = 4

 CarrierId = 5

Desired result should be as mentioned above

like image 428
InTheWorldOfCodingApplications Avatar asked Nov 25 '15 11:11

InTheWorldOfCodingApplications


People also ask

What is a LINQ expression tree?

You can compile and run code represented by expression trees. This enables dynamic modification of executable code, the execution of LINQ queries in various databases, and the creation of dynamic queries. For more information about expression trees in LINQ, see How to use expression trees to build dynamic queries (C#).

Why do we use expression trees?

When you want to have a richer interaction, you need to use Expression Trees. Expression Trees represent code as a structure that you can examine, modify, or execute. These tools give you the power to manipulate code during run time. You can write code that examines running algorithms, or injects new capabilities.


1 Answers

First create a lookup that maps a parent ID to its children:

var lookup = carriers.ToLookup(carrier => carrier.ParentCarrierId);

The go through each node and assign its children based on the lookup:

foreach(var carrier in carriers)
    carrier.Children = lookup[carrier.CarrierId];

To get all of the root nodes just get the null values from the lookup:

var roots = lookup[null];

Note that this entire operation is O(n), as building the lookup is O(n) and all of the children for every single carrier can be found in O(n) time, rather than taking O(n^2) time as in the other solutions posted (as they use an O(n) operation to find all of the children for a single node). This makes this code dramatically faster than the other options, in addition to being much simpler and shorter.

like image 174
Servy Avatar answered Sep 28 '22 23:09

Servy