按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",
}]

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

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

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

卡片,是我的自定义类,它继承自面板对象/类

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

对Cards对象进行排序可以很好地工作,但是,由于我使用的动态函数,我在添加一些处理程序时遇到了很多困难,并且希望在将API结果的数据添加到AppForm中的Cards对象之前对其进行排序。

简而言之,我想按created_atBackups中存储的数据进行排序

提前感谢您的任何意见。

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

这里有一个对我有效的简单方法:

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

最新更新