Home > Enterprise >  Sort Dynamic Object by DateTime c#
Sort Dynamic Object by DateTime c#

Time:02-24

From an API response, I get a JArray result:

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

Backups variable holds the result for me as dynamic. Here is an example of the result I get:

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

I would like to sort the Dynamic Result above by DateTime, and then, I show the result in my form application,

On the form after adding the above result data to an Object, I can sort it using below code:

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

Cards, is my Custom Class and it inherits from Panel Object/Class

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

        public Cards()
        {

        }
    }
}

Sorting Cards object works perfectly, however, due to the dynamic functions I use, I have lot of trouble adding some handlers, and would like to sort the API result before adding its data to the Cards Object in my AppForm.

In Short, I would like to sort the Data stored at Backups by created_at

Thank you in Advance for any input.

CodePudding user response:

I found my answer after some research.

Here is an easy way that worked for me:

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));
    }
}

You can test it here: https://dotnetfiddle.net/4Y96OZ

  • Related