Jared
Jared

Reputation: 2483

LINQ OrderBy/ThenBy ChildrenCollection.SortOrder

EDIT:

Both queries in this example are not ordering by the location sort order. Does anyone have any suggestions on how to do this?

I need some help with ordering an entity collection of groups by a child entity column. I have a one to many relationship from groups to locations.

I need to get the groups ordered by the group name and then by the location sort order.

Since the child entity is a collection I am having trouble.

Here is code I am using that works but returns duplicates:

 var groups = db.GetNavigationGroups()
    .Where(g => selectedLocation > 0 ? g.NavigationGroupLocations.Any(l => l.Location == selectedLocation) : true)
    .SelectMany(g => g.NavigationGroupLocations, (g, l) => new { g, l })
    .OrderBy(x => x.g.Name)
    .ThenBy(x => x.l.SortOrder)
    .Select(x => x.g);

Then I tried this approach using FirstOrDefault():

 List<NavigationGroup> groups = db.DataModel.NavigationGroups
    .Where(g => selectedLocation > 0 ? g.NavigationGroupLocations.Any(l => l.Location == selectedLocation) : true)
    .OrderBy(g => g.Name)
    .ThenBy(g => g.NavigationGroupLocations.Where(l => l.Location == selectedLocation && l.GroupID == g.ID).OrderBy(l => l.SortOrder).FirstOrDefault())
    .ToList();

The problem is that I cannot seem to get the groups in the order I need them to be in based on the locations SortOrder column.

Upvotes: 1

Views: 477

Answers (1)

Bear In Hat
Bear In Hat

Reputation: 1896

The second query you have looks like you're trying to sort by the NavigationGroupLocations object instead of on it's fields. Have you tried:

List<NavigationGroup> groups = db.DataModel.NavigationGroups
.Where(g => selectedLocation > 0 ? g.NavigationGroupLocations.Any(l => l.Location == selectedLocation) : true)
.OrderBy(g => g.Name)
.ThenBy(g => g.NavigationGroupLocations.Where(l => l.Location == selectedLocation && l.GroupID == g.ID).OrderBy(l => l.SortOrder).FirstOrDefault().SortOrder)
.ToList();

You might also want to add your selectedLocation condition to the order clause.

List<NavigationGroup> groups = db.DataModel.NavigationGroups
.Where(g => selectedLocation > 0 ? g.NavigationGroupLocations.Any(l => l.Location == selectedLocation) : true)
.OrderBy(g => g.Name)
.ThenBy(g => g.NavigationGroupLocations.Where(l => selectedLocation > 0 ? l.Location == selectedLocation : true && l.GroupID == g.ID).OrderBy(l => l.SortOrder).FirstOrDefault().SortOrder)
.ToList();

Upvotes: 1

Related Questions