为什么Linq GroupBy在OrderBy之后取消了订单操作?

问题描述:

我有一个 Action 模型,该模型具有 Session 导航属性

I have a Action model with Session Navigation Property,

考虑以下代码:

var x=db.Actions.OrderBy(p => p.Session.Number).ThenBy(p => p.Date);//it's OK

x是有序操作,但是在x上分组时,不能在有序可枚举的基础上手动在x上进行迭代(基于 Action.Session ):

x is a ordered Action, but when grouped on x, group not iterate on x(base on Action.Session) manually on ordered enumerable:

var y=x.GroupBy(p=>p.Session).ToArray()

y有一组会话(Key,IGrouping),但是为什么基于 Session.Number 分组未排序?

y have a group(Key,IGrouping) of sessions but why group.Key not ordered base on Session.Number?

我如何按编号到达一组会话订单,按日期排列每个分组?

因为它是 Enumerable.GroupBy 保留顺序.没有为 Queryable.GroupBy . 从前者的文档中:

Because it's Enumerable.GroupBy that preserves order. No such promise is made for Queryable.GroupBy. From the documentation of the former:

IGrouping(Of TKey,TElement)对象的生成顺序基于 产生每个元素的第一个键的源中元素的顺序 IGrouping(Of TKey,TElement).分组中的元素按顺序产生 它们出现在源代码中.

The IGrouping(Of TKey, TElement) objects are yielded in an order based on order of the elements in source that produced the first key of each IGrouping(Of TKey, TElement). Elements in a grouping are yielded in the order they appear in source.

您正在调用后者,但未提及上述内容.在GroupBy之后调用OrderBy使其正常工作.

You're calling the latter, and the above is not mentioned. Call OrderBy after GroupBy to make it work.

更新:由于您显然希望对GroupBy键进行排序,因此您应该能够使用另一个GroupBy重载来指定要对每个会话的操作列表进行排序:>

Update: since you apparently want to sort on more than just the GroupBy key, you should be able to use another GroupBy overload to specify that each session's list of actions is to be sorted:

db.Actions.GroupBy(
    p => p.Session,
    (session, actions) => new {
        Session = session,
        Actions = actions.OrderBy(p => p.Date)
    }).OrderBy(p => p.Session.Number).ToArray();