执行父则子类中的LINQ [英] Performing a Parent then Child sort in Linq

查看:192
本文介绍了执行父则子类中的LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其目的是到列表父排序,然后孩子(只会有一个孩子)。

 实例设置:
ID的ParentId类型单位
1 NULL能源千焦耳
2 1卡
3空G蛋白
4 NULL脂肪,总克
5 4饱和克
6 NULL碳水化合物克
7 6糖摹
8 NULL膳食纤维克
10 NULL钠毫克
11 NULL钾毫克
 

因此​​,举例来说,如果我按类型排序(按字母顺序排列)那就拿出

  1. 碳水化合物
  2. 糖(父= 1)。
  3. 膳食纤维
  4. 能源
  5. 在卡尔(父= 4。)
  6. 脂肪,总
  7. 在饱和(父= 6)。
解决方案

试试这个:

 返回myData.Select(X =>新建{键=(x.Parent ?? x)的型号及项目= X})
             .OrderBy(X => x.key)
             .ThenBy(X =>!x.item.Parent = NULL)
             。选择(X => x.item);
 

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.)

解决方案

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

这篇关于执行父则子类中的LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆