按日期时间排序动态对象 c#

Sort Dynamic Object by DateTime c#

从 API 响应中,我得到一个 JArray 结果:

dynamic Backups = JArray.Parse(result.Content.ReadAsStringAsync().Result.ToString());

Backups 变量为我保存了动态的结果。这是我得到的结果示例:

[{
    "bu_region": "US",
    "created_at": "2022-01-04 00:06:09",
    "is_automate": "0",
    "bu_snapshot_name": "null",
    "plugin_v": "4.5.2",
},
{
    "bu_region": "US",
    "created_at": "2022-02-20 00:07:55",
    "is_automate": "0",
    "bu_snapshot_name": "null",
    "plugin_v": "4.5.2",
},
{
    "bu_region": "US",
    "created_at": "2021-12-31 00:05:31",
    "is_automate": "0",
    "bu_snapshot_name": "null",
    "plugin_v": "4.5.2",
}]

我想按日期时间对上面的动态结果进行排序,然后在我的表单应用程序中显示结果,

在将上述结果数据添加到对象后的表单上,我可以使用以下代码对其进行排序:

List<Cards> sortedListByDate = listCards.OrderBy(s => s.DateOfCreation.Date).ToList();

Cards,是我的 Custom Class,它继承自 Panel Object/Class

namespace WinFormsApp1
{
    public class Cards : Panel
    {
        public DateTime DateOfCreation { get; set; }
        public TimeSpan TimeOfCreation { get; set; }

        public Cards()
        {

        }
    }
}

对 Cards 对象进行排序非常有效,但是,由于我使用的是动态函数,我在添加一些处理程序时遇到了很多麻烦,并且想在将其数据添加到 Cards 对象之前对 API 结果进行排序在我的 AppForm 中。

简而言之,我想按 created_at[ 对存储在 Backups 的数据进行排序=35=]

提前感谢您的任何意见。

经过一番研究,我找到了答案。

这是一个对我有用的简单方法:

using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
                    
public class Program
{
    public static void Main()
    {
        string json = @"
        [{
            ""bu_region"": ""US"",
            ""created_at"": ""2022-01-04 00:06:09"",
            ""is_automate"": ""0"",
            ""bu_snapshot_name"": ""null"",
            ""plugin_v"": ""4.5.2"",
        },
        {
            ""bu_region"": ""US"",
            ""created_at"": ""2022-02-20 00:07:55"",
            ""is_automate"": ""0"",
            ""bu_snapshot_name"": ""null"",
            ""plugin_v"": ""4.5.2"",
        },
        {
            ""bu_region"": ""US"",
            ""created_at"": ""2021-12-31 00:05:31"",
            ""is_automate"": ""0"",
            ""bu_snapshot_name"": ""null"",
            ""plugin_v"": ""4.5.2"",
        }]";
        
        JArray array = JArray.Parse(json);
        
        JArray sorted = new JArray(array.OrderBy(obj => (DateTime)obj["created_at"]));
        
        Console.WriteLine(sorted.ToString(Formatting.Indented));
    }
}

你可以在这里测试: https://dotnetfiddle.net/4Y96OZ