Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何对Linq查询分组结果进行排序_Linq_Sorting_Group By - Fatal编程技术网

如何对Linq查询分组结果进行排序

如何对Linq查询分组结果进行排序,linq,sorting,group-by,Linq,Sorting,Group By,我有一个查询,它返回一个按Univers分组并按Univers名称排序的类别列表。我希望结果列表也按类别名称(C.name)排序,以下是我的Linq查询: public static IEnumerable<IGrouping<String, String>> GetCatalogUnivCateg(){ var contexte = new AV2_Entities(); var query = from C in contexte.Catego

我有一个查询,它返回一个按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();
   }
公共静态IEnumerable getCatalogNivCateg(){
var contexte=新的AV2_实体();
var query=来自contexte.Category中的C
组C.名称由C.Univers.Name转换为g
orderby g.Key
选择g;
返回query.ToList();
}

我想了解当结果具有orderby时,group by是如何应用的。

选择group时添加ordering:

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
,则无法返回排序结果。另外,
i分组
实现是内部的,所以不能只返回一些新的分组对象。我建议您创建DTO类,如:

public class UniversCategories
{
    public string UniversName { get; set; }
    public IEnumerable<string> Categories { get; set; }
}

谢谢,我理解选择后的Orderby,但是我对投影感到困惑,因为我想得到一个IEnumerable@Bro为什么需要
i分组
type?这将返回
IEnumerable
如果您还需要密钥,您可以选择匿名类型
select new{UniversName=g.Key,Categories=g.OrderBy(x=>x.Name)。select(x=>x.Name)}
(我将用此代码更新答案)
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)
            };