目的是按父母排序列表,然后是孩子(只有一个孩子)。
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
因此,例如,如果按类型(字母顺序)排序,它会出现
答案 0 :(得分:4)
试试这个:
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);
答案 1 :(得分:1)
这可以分两步完成。首先 - 构建父子层次结构(并对其进行排序):
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<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;
}
}
答案 2 :(得分:0)
这应该有效
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;