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.
By specifying the key parameter of sort() or sorted() , you can sort a list of dictionaries according to the value of the specific key.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With