在我的代码中,我需要根据日期对JObject
数组进行排序。怎么做?我的数据如下所示,我需要将其按降序排序。
"His": [
{
"Date": "6/17/2019 6:00:00 PM",
"StatusMsg": ""
},
{
"Date": "6/17/2019 11:08:48 AM",
"StatusMsg": ""
},
{
"Date": "6/17/2019 7:38:00 AM",
"StatusMsg": ""
},
{
"Date": "6/17/2019 5:00:00 AM",
"StatusMsg": ""
},
{
"Date": "6/16/2019 6:16:00 PM",
"StatusMsg": ""
},
{
"Date": "6/15/2019 9:20:00 PM",
"StatusMsg": ""
},
{
"Date": "6/13/2019 2:00:00 PM",
"StatusMsg": ""
},
{
"Date": "6/13/2019 1:37:00 PM",
"StatusMsg": ""
},
{
"Date": "6/13/2019 2:39:00 AM",
"StatusMsg": ""
},
{
"Date": "6/13/2019 2:11:00 AM",
"StatusMsg": ""
},
{
"Date": "6/13/2019 2:08:00 AM",
"StatusMsg": ""
},
{
"Date": "6/12/2019 3:50:00 PM",
"StatusMsg": ""
}
]
我将结果分配给JObject
。这是我的示例输入。任何人都可以帮助我。谢谢。
答案 0 :(得分:4)
就像马克在问题注释中所说的-为什么不使用常规类:
public class Rootobject
{
public His[] His { get; set; }
}
public class His
{
public string Date { get; set; }
public string StatusMsg { get; set; }
public string Msg { get; set; }
public string StatusDate { get; set; }
}
反序列化并利用LINQ:
var json = "{\r\n\t\"His\": [\r\n {\r\n \"Date\": \"3/18/2019 6:30:45 PM\",\r\n \"StatusMsg\": \"test3\"\r\n },\r\n {\r\n \"Date\": \"3/21/2019 12:13:02 PM\",\r\n \"Msg\": \"test2\"\r\n },\r\n {\r\n \"StatusDate\": \"3/17/2019 9:26:00 AM\",\r\n \"Msg\": \"test1\"\r\n },\r\n ]\r\n}";
var obj = JsonConvert.DeserializeObject<Rootobject>(json);
var sortedList = obj.His.OrderByDescending(o => o.Date).ToList();
编辑:如果您不想使用课程,则可以执行以下操作:
var json = "{\r\n\t\"His\": [{\r\n\t\t\t\"Date\": \"3/18/2019 6:30:45 PM\",\r\n\t\t\t\"StatusMsg\": \"test3\"\r\n\t\t}, {\r\n\t\t\t\"Date\": \"3/21/2019 12:13:02 PM\",\r\n\t\t\t\"Msg\": \"test2\"\r\n\t\t}, {\r\n\t\t\t\"Date\": \"3/17/2019 9:26:00 AM\",\r\n\t\t\t\"Msg\": \"test1\"\r\n\t\t},\r\n\t]\r\n}\r\n";
JObject jobj = JObject.Parse(json);
JArray array = jobj["His"];
JArray sorted = new JArray(array.OrderByDescending(obj => (DateTime)obj["Date"]));
这假定每个JSON对象将始终具有名为“日期”的属性