Home > Enterprise >  How to sort a dictionary based on date key value
How to sort a dictionary based on date key value

Time:09-30

I have a dictionary, which is a nested dictionary. I want to sort it according to the date and time provided in the dictionary. how to do this is c#. Here is my code

foreach (var user in Load_User)
            {
                
                if(user.Value.Projects[0].type=="0")
                {
                    print("Standard User");
                    
                    
                     _Standard_User.Add(user.Key, new Dictionary<string, string>() { 
                               { "Email", user.Value.Email },
                               { "age",user.Value.age},
                               {"userName", user.Value.userName},
                               {"mobile", user.Value.mobile},
                               {"instagram_handle",user.Value.instagram_handle},
                               { "City_Of_Residence", user.Value.City_Of_Residence },
                               { "nationality", user.Value.nationality },
                               { "No_of_Votes", user.Value.No_of_Votes.ToString()},
                               {"Brief",user.Value.Projects[0].Brief},
                               {"Creation_Date", user.Value.Projects[0].Creation_Date},
                               {"Creation_Time", user.Value.Projects[0].Creation_Time},
                               {"type", user.Value.Projects[0].type},
                               {"localId",user.Value.localId},
                               {"thumbnail_image",user.Value.Projects[0].thumbnail_image}
                            });

                }   

CodePudding user response:

You can do this using LINQ (make sure to include the System.Linq namespace):

_Standard_User.OrderBy(x => Convert.ToDateTime(x.Value["Creation_Date"]).Add(TimeSpan.Parse(x.Value["Creation_Time"])))
              .ToDictionary(x => x.Key, x => x.Value);

This will return the dictionary, sorted by both the creation date and time. This expects the Creation_Date to be parseable by Convert.ToDateTime (a format like 2022-09-30), and Creation_Time to be parseable by TimeSpan.Parse (a format like 10:38).

If you have the exact format, you can utilize TimeSpan.ParseExact which will bypass any culture issues:

_Standard_User.OrderBy(x => DateTime.ParseExact(x.Value["Creation_Date"], "yyyy-MM-dd", null).Add(TimeSpan.Parse(x.Value["Creation_Time"])))
              .ToDictionary(x => x.Key, x => x.Value);

The snippet above will be functionally equal to the previous snippet, but it will expect dates in the format of year-month-day.

  • Related