score:2
Accepted answer
You could use a recursive method, starting with items without a parent id:
var categories = new List<Category>();
GetCategories(ref categories);
void GetCategories(ref List<Category> categories, int? parentId = null)
{
string query = string.Empty;
if (parentId.HasValue)
{
query = "SELECT * FROM categories WHERE parentid=@parentid";
}
else
{
query = "SELECT * FROM categories WHERE parentid IS NULL";
}
using (var conn = new SqlConnection(connStr))
{
using (var command = new SqlCommand(query, conn))
{
conn.Open();
if (parentId.HasValue)
{
command.Parameters.AddWithValue("@parentid", parentId.Value);
}
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var c = new Category();
c.text = reader["text"];
//etc..
categories.Add(c);
c.children = new List<Category>();
GetCategories(ref c.children, c.id);
}
}
}
}
}
score:0
Try this
var allCategories = new List<Category>();
After fetching data...
var children = allCategories.ToLookup(cat => cat.ParentId);
foreach (var category in allCategories)
{
category.Children = children[category.ParentId].ToList();
}
score:0
Flat List to Hierarchy
public class TreeObject
{
public int ID { get; set; }
public int ParentID { get; set; }
public string Name { get; set; }
public List<TreeObject> Children { get; set; } = new List<TreeObject>();
}
Send flat list to this method and get hierarchy (parent/child) object list
public List<TreeObject> FlatToHierarchy(List<TreeObject> list)
{
var lookup = new Dictionary<int, TreeObject>();
var nested = new List<TreeObject>();
foreach (TreeObject item in list)
{
if (lookup.ContainsKey(item.ParentID))
{
// add to the parent's child list
lookup[item.ParentID].Children.Add(item);
}
else
{
// no parent added yet (or this is the first time)
nested.Add(item);
}
lookup.Add(item.ID, item);
}
return nested;
}
Source: stackoverflow.com
Related Articles
- LINQ query to group parent and child elements
- Select Parent XML Elements based on Child element values LINQ C#
- How can I fetch child entities as DTO in parent using reusable queries/Expression's with EF code first?
- Grouping a list of objects by parent using linq to output child elements
- Selecting nth child element based on parent elements attribute
- most efficient Entity Framework Code First method of flattening / projecting parent entity with specific child
- displaying parent-child elements hierarchically in c#
- XML reading repeating child elements with same name as parent c#
- How to add Parent node if Child node elements are equal?
- Add xml child elements to specific parent node in C# with linq
- linq query to get all child elements by passing parent id
- C#, LINQ Getting Child elements of a Specified Parent Element
- Create a tree structure in linq with a single list source with parent - child as strings of an object
- C# Linq XML Query where multiple elements of same name from a parent node based on a child node value
- LINQ XML - Select all parent elements where a child has a given value
- How do I retrieve the value of an attribute in a parent if one of the elements of a child equals to a value?
- Get xml child elements from parent via button to new form
- Linq to Select Parent Objects Where Child Objects Have a Matching Child Object
- linq how to select a parent with a child collection that contains one or many of an array (or list) of values
- Find child objects in list of parent objects using LINQ
- Linq recursive parent child
- Order list by parent and child items
- How to understand the following C# linq code of implementing the algorithm to return all combinations of k elements from n
- Performing a Parent then Child sort in Linq
- Linq group by parent property order by child
- Order parent collection by minimum values in child collection in Linq
- Order parent object list by child list attribute
- Parse XML with LINQ to get child elements
- Joining parent and child collection in LINQ for a single merged output
- Linq projection of flattened table into parent and child object graph
- Converting lambda expression into an expression tree
- How to query MongoDb Collection with C# Driver by having dictionary values as filter parameters
- How to Return LINQ results and display in view?
- LINQ - Different results with LINQ to SQL vs LINQPad
- Linq Paging - How to incorporate total record count
- Amazon Marketplace XML parsing with LINQ
- Linq object properties disappear after serialization
- Imroving/Modifying LINQ query
- Linq to entities ignore casing, NotSupportedException
- Dynamic Linq Query and Expression
- Linq most efficient top results
- How to search a list of objects for a specific string attribute using LINQ in C#
- Linq returning value from adjacent column
- how to combine and sum up the result from two lists based on unique id
- How to convert data from two tables get from Linq query to List witch can be populated in wpf form
- Select multiple table with Linq to Sql
- LINQ with Sub Query, Group By, and Having
- Linq insert many to one rows
- Combine two lists of entities with a condition
- Group by NOT having element in common?