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 Query
- 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
More Query from same tag
- Error on result of linq expression (and anounymous type)
- App_Data folder shadow folder empty
- how to return Json with a list from other classes?
- How to get the list elements that are not into another list C#
- Linq Expression change data storing
- How to only select items from a list with certain property set to true
- LINQ Grouping or Splitting
- Is it possible to detect if the selected item is the first in LINQ-to-SQL?
- Iinq equivalent to stored procedure
- LINQ to XML issue with converting a tree to a list
- LINQ MVC 3 and double query in profiler
- Pivot and Unpivot in LINQ Core
- Grouping by a field in DocumentDB
- Increment outer loop from inner loop in C# using Foreach
- C# iteration and interpolation syntax
- How to sort a list with the values of another list with Linq
- How to get all properties with an specific name and create a List<KeyValuePair<string,string>>
- VB.NET Returns IEnumerable(Of IEnumerable(Of T)) when Using Group By LINQ Statement
- The expression 'y.Cases' is invalid inside an 'Include' operation
- Can I define Default Sort order in LinQ
- How get by EF LINQ flattened records but take only one record by field priority if there are duplicates
- LINQ - limit size by group
- What Should I know to underestand LINQ better?
- Variable to which Linq Query assigned has never the value of NULL
- Names disintct in linq
- Linq-asp.net Core- Get the only one row after grouping
- Why does not null in LINQ query still return null records?
- Join 2 table and just display the active column
- How to create an IQueryable Web API that can pull data from several data sources?
- Replace on inner property of IEnumerable of objects