我有一个问题,在那里谈到自定义排序。
我需要根据3个因素对元素进行排序:
- ID(字符串)
1.标志(布尔)
1.日期(日期时间
小提琴代码示例:https://dotnetfiddle.net/OSicuK
样本数据记录:
{
"id": "cbb440a8-fc26-4d30-966c-eba114410c6b",
"creationDate": "2021-05-25T00:00:00",
"child": false,
"parentId": "cbb440a8-fc26-4d30-966c-eba114410c6b"
},
{
"id": "cf70fbef-aa4f-45d3-96ab-3e211c290765",
"creationDate": "2021-05-27T00:00:00",
"child": true,
"parentId": "cbb440a8-fc26-4d30-966c-eba114410c6b"
},
{
"id": "48a82712-3e72-3ca7-a02d-edafd170f0b5",
"creationDate": "2021-06-17T00:00:00",
"child": false,
"parentId": "48a82712-3e72-3ca7-a02d-edafd170f0b5"
},
{ (this one should be ealier since creationDate is ealier than one above and both child is set to false)
"id": "1e4372f9-54dd-45b1-a401-56accbefc936",
"creationDate": "2021-05-25T00:00:00",
"child": false,
"parentId": "1e4372f9-54dd-45b1-a401-56accbefc936"
},
{
"id": "cf70fbef-aa4f-45d3-96ab-3e211c290765",
"creationDate": "2021-05-27T00:00:00",
"child": true,
"parentId": "1e4372f9-54dd-45b1-a401-56accbefc936"
},
{
"id": "82d7ea62-8f30-4bfd-be27-eb79c0f5e9e9",
"creationDate": "2021-05-27T00:00:00",
"child": true,
"parentId": "1e4372f9-54dd-45b1-a401-56accbefc936"
},
{
"id": "48a82712-3e72-3ca7-a02d-edafd170f0b5",
"creationDate": "2021-06-17T00:00:00",
"child": true,
"parentId": "1e4372f9-54dd-45b1-a401-56accbefc936"
}
记录需要从最早的父记录到最新的父记录排序,当子标记设置为假时,记录需要位于具有相同parentId但子标记设置为真的所有记录之前。
我试过了:return documents .OrderBy(x => x.parentId) .ThenBy(x => x.child) .ThenBy(x => x.creationDate);
很遗憾,CreationDate排序不正确。
先谢了!
2条答案
按热度按时间lh80um4z1#
你漏掉的是数据的分组。
如果不分组,您可以在
ParentId
或CreationDate
上排序,但您希望按照父节点的CreationDate
顺序对父节点及其子节点进行排序(即分组)。ffscu2ro2#
您所面临的问题可以通过更改排序顺序来解决。您可以使用
OrderByDescending
代替OrderBy
。下面是示例代码:-