LINQ Group然后是OrderBy Behavior

Vis*_*and 3 c# linq c#-4.0

我有一个场景,我必须首先分组,然后对每个组进行排序.我提出了以下工作查询:

applicants = context.Applicants
                    .OrderBy(app => app.Id).Skip((pageNumber - 1)*defaultPageSize)
                    .Take(defaultPageSize)
                    .GroupBy(app => app.PassportNumber)
                    .Select(g => g.OrderBy(d => d.IsEndorseChild)).ToList()
                    .SelectMany(grouping => grouping)
                    .ToList();
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

applicants = context.Applicants
                    .OrderBy(app => app.Id).Skip((pageNumber - 1)*defaultPageSize)
                    .Take(defaultPageSize)
                    .GroupBy(app => app.PassportNumber)
                    .Select(g => g.OrderBy(d => d.IsEndorseChild))
                    .SelectMany(grouping => grouping)
                    .ToList();
Run Code Online (Sandbox Code Playgroud)

第一个查询产生结果(这些是返回的申请人的Id),如:
7, 10, 8, 2, 9, 6, 5, 3, 4, 1
但第二个查询产生:
7, 10, 8, 2, 9, 6, 3, 4, 5, 1

我不确定为什么会发生这种情况以及查询之间有什么区别.
我到底错过了什么?

编辑:示例输入和预期输出:

Applicant 1 => ID : 1
               IsEndorsed : 0
               Passport : ABC123

Applicant 2 => ID : 2
               IsEndorsed : 1
               Passport : ABC123


Applicant 3 => ID : 3
               IsEndorsed : 0
               Passport : ABC1234

Applicant 4 => ID : 4
               IsEndorsed : 0
               Passport : A1234

Applicant 5 => ID : 5
               IsEndorsed : 1
               Passport : PQR123
Applicant 6 => ID : 6
               IsEndorsed : 1
               Passport : PQR123
Applicant 7 => ID : 7
               IsEndorsed : 0
               Passport : PQR123


Expected output  : (Grp by Passport Number and in each group IsEndorsed = 0 is at top)
----------------------------------------------

Applicant 1 => ID : 1
               IsEndorsed : 0
               Passport : ABC123

Applicant 2 => ID : 2
               IsEndorsed : 1
               Passport : ABC123

Applicant 3 => ID : 3
               IsEndorsed : 0
               Passport : ABC1234

Applicant 4 => ID : 4
               IsEndorsed : 0
               Passport : AX1234

Applicant 7 => ID : 7
               IsEndorsed : 0
               Passport : PQR123

Applicant 5 => ID : 5
               IsEndorsed : 1
               Passport : PQR123
Applicant 6 => ID : 6
               IsEndorsed : 1
               Passport : PQR123
Run Code Online (Sandbox Code Playgroud)

Dan*_*rth 8

您按布尔值排序.只要一个组中的两个值IsEndorseChild相对于彼此具有相同的顺序值,通常是未定义的.

OrderBy实际上被转换为SQL ORDER BY,因此结果还取决于ORDER BY您正在使用的数据库的实现.它可能是稳定的或不稳定的.
不稳定意味着它可以按任何顺序返回具有相同有序值的行.
稳定意味着它将以与输入相同的顺序返回它们.

例如,SQL Server具有不稳定的排序:SQL order by子句是否保证稳定(按标准)

所以,我的结论是,ToList调用 - 两个查询中唯一的区别 - 对结果没有影响.差异仅仅是由于不稳定的排序造成的.