Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing a Parent then Child sort in Linq

The intention is to sort the list by the parent, and then the child (there will only be 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 (alphabetical order) it would come up

  1. Carbohydrate
  2. Sugars (parent = 1.)
  3. Dietary fibre
  4. Energy
  5. Cal (parent = 4.)
  6. Fat, total
  7. Saturated (parent = 6.)
like image 900
ediblecode Avatar asked Oct 19 '12 14:10

ediblecode


2 Answers

Try this:

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);
like image 79
Bobson Avatar answered Nov 04 '22 04:11

Bobson


This could be done in two steps. First - building parent-child hierarchy (and sorting it):

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 };

Second - flattering hierarchy

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

For flattering I used 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;
    }
}    
like image 1
Sergey Berezovskiy Avatar answered Nov 04 '22 03:11

Sergey Berezovskiy