1

编辑:

此示例中的两个查询都不是按位置排序顺序排序的。有人对如何做到这一点有任何建议吗?

我需要一些帮助来按子实体列对组的实体集合进行排序。我有从组到位置的一对多关系。

我需要按组名排序,然后按位置排序顺序。

由于子实体是一个集合,我遇到了麻烦。

这是我正在使用但返回重复项的代码:

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

然后我使用 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();

问题是我似乎无法根据位置 SortOrder 列按我需要它们的顺序获取组。

4

1 回答 1

1

您的第二个查询看起来像是在尝试按 NavigationGroupLocations 对象而不是按其字段进行排序。你有没有尝试过:

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

您可能还想将您的 selectedLocation 条件添加到 order 子句中。

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();
于 2012-04-17T16:59:56.617 回答