在Linq中执行Parent然后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
因此,例如,如果我按类型(字母顺序)排序,它就会出现
- 糖类
- 糖(父母= 1.)
- 膳食纤维
- 能源
- Cal(父= 4)
- 胖,总
- 饱和(父= 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);
这可以分两步完成。 首先 – 构建父子层次结构(并对其进行排序):
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 };
第二 – 讨人喜欢的等级制度
var result = query.Flatten(x => x.Parent, x => x.Children);
为了奉承我使用的扩展方法:
public static IEnumerable Flatten( this IEnumerable sequence, Func parentSelector, Func> childrenSelector) { foreach (var element in sequence) { yield return parentSelector(element); foreach (var child in childrenSelector(element)) yield return child; } }
这应该工作
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;