繁体   English   中英

LINQ Group然后是OrderBy Behavior

[英]LINQ GroupBy then OrderBy Behaviour

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

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

但这不起作用:

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

第一个查询生成结果(这些是返回的申请人的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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM