我无法复制您的简单 Where - OrderByDescending 问题。在我的情况下(Id 是一个 int)序列是正确排序的。
所以我专注于你的第一个问题。
如果在我看来,您希望从您的 RentBillRegisters 序列、每个使用的 ClientId、RentBillRegister 中获得最高的 Id。
您首先对所有RentBillRegisters 进行排序,按ID 降序排列;然后你将所有RentBillRegisters 分组到相同的ClientId 组中,并从每个组中获取第一个元素。这应该是该组中 ID 最高的 RentBillRegister。
Id | ClientId
01 | A
02 | B
03 | A
04 | A
05 | C
06 | B
// After ordering by descending Id:
[06 B] [05 C] [04 A] [03 A] [02 B] [01 A]
// After grouping by ClientId and from every group take the first
group B: [06 B] [02 B] => [06 B]
group C: [05 C] => [05 C]
group A: [04 A] [03 A] [01 A] => [04 A]
如果 RentBillRegister A 和 B 最终会在不同的组中,您为什么要比较它们来订购它们?先对项目进行分组,然后对每个组中的项目进行排序不是更有效吗?
var result = dbContextRent.RentBillRegisters
.Where(...)
// make groups of RentBillRegisters that have the same ClientId
.GroupBy(rentBillRegister => rentBillRegister.ClientId
// ResultSelector: take the clientId that was selected as key
// and all rentBillRegisters with this clientId to create a new object
(clientId, rentBillRegistersWithThisClientId) =>
// I don't want all RentBillRegisters With This ClientId,
// I want only the one with the highest Id
// = the first after sorting by Id in descending order
// Nota Bene: I don't use the Key (ClientId) anymore
rentBillRegistersWithThisClientId
.OrderByDescending(rentBillRegister => rentBillRegister.Id)
.FirstOrDefault(),
})
// now you have from all `RentBillRegisters` with the same clientId the one
// with the highest Id. The groups are not ordered yet:
.OrderByDescending(rentBillRegisterWithHighestId => rentillRegisterWithHighesId.ClientId);
从上面的集合中:
// Make Groups with same ClientId, order and take the first
Group by ClientId | After Ordering | Take First
Group with ClientId A | [04 A] [03 A] [01 A] | [04 A]
Group with ClientId B | [06 B] [02 B] | [06 B]
Group with ClientId C | [05 C] | [05 C]
// Order the groups by descending Id:
[06 B] [05 C] [04 A]