Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort List of Dictionaries

I have a collection of dictionary values (a List<>) that I need to sort. Basically each dictionary is a 'row' and the collection is a page of rows. A simple example;

       var data = new List<Dictionary<string,string>>();
       data.Add(new Dictionary<string,string>() {
                    { "Firstname", "Bob"},
                    { "Lastname", "Banana"}
       });
       data.Add(new Dictionary<string, string>() {
                    { "Firstname", "Amy"},
                    { "Lastname", "Apple"}
       });
       data.Add(new Dictionary<string, string>() {
                    { "Firstname", "Charlie"},
                    { "Lastname", "Coconut"}
       });
       data.Add(new Dictionary<string, string>() {
                    { "Firstname", "Andy"},
                    { "Lastname", "Apple"}
       });

The sort string generated is "SQL" like, example

 Lastname asc, Firstname desc

I have tried .OrderBy() on the data object but that doesn't seem to work right against the KeyValuePairs.

Any idea how I could get the data list to be sorted to be in this order, using the dynamic sort statement:

 Apple, Andy
 Apple, Amy
 Banana, Bob
 Coconut, Charlie

Using .NET 4.0 if some fancy LINQ will work. Thanks for any suggestions.

like image 566
CmdrTallen Avatar asked Jun 27 '11 22:06

CmdrTallen


People also ask

Can you sort a list of dictionaries?

By specifying the key parameter of sort() or sorted() , you can sort a list of dictionaries according to the value of the specific key.

Can you sort dictionaries in Python?

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.

How do you sort dictionaries in Python dictionary?

Sort Dictionary Using the operator Module and itemgetter() This function returns the key-value pairs of a dictionary as a list of tuples. We can sort the list of tuples by using the itemgetter() function to pull the second value of the tuple i.e. the value of the keys in the dictionary.

How do you sort list by key?

Sort with custom function using key If you want your own implementation for sorting, the sort() method also accepts a key function as an optional parameter. Based on the results of the key function, you can sort the given list.


1 Answers

  private static IEnumerable<Dictionary<string, string>> Sort(IEnumerable<Dictionary<string,string>> data, string orderByString)
  {
     var orderBy =
        orderByString.Split(',').Select(
           s => s.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries))
           .Select (a => new {Field=a[0],Descending = "desc".Equals (a[1], StringComparison.InvariantCultureIgnoreCase)})
           .ToList ();
     if (orderBy.Count == 0)
        return data;
     // First one is OrderBy or OrderByDescending.
     IOrderedEnumerable<Dictionary<string, string>> ordered =
        orderBy[0].Descending ? data.OrderByDescending (d => d[orderBy[0].Field]) : data.OrderBy (d => d[orderBy[0].Field]);
     for (int i = 1; i < orderBy.Count; i++)
     {
        // Rest are ThenBy or ThenByDescending.
        var orderClause = orderBy[i];
        ordered =
           orderBy[i].Descending ? ordered.ThenByDescending(d => d[orderClause.Field]) : ordered.ThenBy(d => d[orderClause.Field]);
     }
     return ordered;
  }
like image 120
agent-j Avatar answered Oct 07 '22 09:10

agent-j