Doing parent then sorting descendants in Linq

The goal is to sort the list by parent and then by child (there will be only one child).

Example Set: ID ParentId Type Unit 1 NULL Energy kJ 2 1 Cal 3 NULL Protein g 4 NULL Fat, total g 5 4 Saturated g 6 NULL Carbohydrate g 7 6 Sugars g 8 NULL Dietary fibre g 10 NULL Sodium mg 11 NULL Potassium mg 

So, for example, if I sort by type (in alphabetical order), it will look

  • Carbohydrates
  • Sugars (parent = 1.)
  • Diet fiber
  • Energy
  • Cal (parent = 4.)
  • Fat, total
  • Saturated (parent = 6.)
+8
c # linq linq-to-sql
source share
3 answers

Try the following:

 return myData.Select(x => new { key = (x.Parent ?? x).Type, item = x}) .OrderBy(x => x.key) .ThenBy(x => x.item.Parent != null) .Select(x => x.item); 
+4
source share

This can be done in two stages. The initial parent-child hierarchy (and sorting):

 var query = from parent in data where parent.ParentId == null orderby parent.Type join child in data on parent.ID equals child.ParentId into g select new { Parent = parent, Children = g }; 

The second is a flattering hierarchy

 var result = query.Flatten(x => x.Parent, x => x.Children); 

For flattering, I used the extension method:

 public static IEnumerable<TResult> Flatten<T, TResult>( this IEnumerable<T> sequence, Func<T, TResult> parentSelector, Func<T, IEnumerable<TResult>> childrenSelector) { foreach (var element in sequence) { yield return parentSelector(element); foreach (var child in childrenSelector(element)) yield return child; } } 
+1
source share

This should work

 var query = from p in context.Table from c in context.Table.Where(x => p.ID == x.ParentId) .DefaultIfEmpty() let hasNoParent = c == null orderby hasNoParent ? p.Type : c.Type, hasNoParent ? 0 : 1 select hasNoParent ? p.Type : c.Type; 
0
source share

All Articles