在Linq中执行Parent然后Child排序

edi*_*ode 8 .net c# linq linq-to-sql

目的是按父项对列表进行排序,然后是子项(只有一个子项).

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
Run Code Online (Sandbox Code Playgroud)

因此,例如,如果我按类型(字母顺序)排序,它就会出现

  1. 糖类
  2. 糖(父母= 1.)
  3. 膳食纤维
  4. 能源
  5. Cal(父母= 4.)
  6. 胖,总
  7. 饱和(父= 6)

Bob*_*son 6

尝试这个:

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);
Run Code Online (Sandbox Code Playgroud)