我有一个查询,它返回按Univers分组的类别列表,并按Univers名称排序。我希望结果列表也按类别名称(C.Name)排序,这是我的Linq查询:
public static IEnumerable<IGrouping<String, String>> GetCatalogUnivCateg(){
var contexte = new AV2_Entities();
var query = from C in contexte.Category
group C.Name by C.Univers.Name into g
orderby g.Key
select g;
return query.ToList();
}
我想了解当结果有一个orderby时,如何应用group by。
答案 0 :(得分:2)
选择组时添加顺序:
var query = from c in contexte.Category
group c by c.Univers.Name into g
orderby g.Key
select g.OrderBy(x => x.Name) // sort by name
.Select(x => x.Name); // project if you need just names
不幸的是,如果从方法返回IGrouping
,则无法返回排序结果。此外IGrouping
实现是内部的,因此您不能只返回一些新的分组对象。我建议你创建DTO类,如:
public class UniversCategories
{
public string UniversName { get; set; }
public IEnumerable<string> Categories { get; set; }
}
从您的方法返回此类的实例
var query = from c in contexte.Category
group c by c.Univers.Name into g
orderby g.Key
select new UniversCategories {
UniversName = g.Key,
Categories = g.Select(x => x.Name).OrderBy(n => n)
};