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
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);
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With