.net 基于不同参数在CosmosDB中排序

h9vpoimq  于 2023-02-06  发布在  .NET
关注(0)|答案(2)|浏览(102)
    • bounty将在6天后过期**。回答此问题可获得+100的声誉奖励。Krzysztof正在寻找来自声誉良好的来源的答案

我有一个问题,在那里谈到自定义排序。
我需要根据3个因素对元素进行排序:

  1. 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排序不正确。
先谢了!

lh80um4z

lh80um4z1#

你漏掉的是数据的分组。
如果不分组,您可以在ParentIdCreationDate上排序,但您希望按照父节点的CreationDate顺序对父节点及其子节点进行排序(即分组)。

var results = list
    .OrderBy(x => x.CreationDate)
    .ThenBy(x => x.Child)
    .GroupBy(x => x.ParentId)
    .SelectMany(x => x);
ffscu2ro

ffscu2ro2#

您所面临的问题可以通过更改排序顺序来解决。您可以使用OrderByDescending代替OrderBy
下面是示例代码:-

return documents.OrderByDescending(x => x.parentId).ThenBy(x =>
 x.child).ThenBy(x => x.creationDate);

相关问题