2

I have a query that returns me a list of Categories grouped by Univers and ordered by Univers name. I would like the list of results also being ordered by category name (C.Name), here is my Linq query:

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

I would like to understand how is applied the group by, when the results has an orderby.

4

1 回答 1

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)
            };
于 2013-07-09T13:45:46.577 回答