Reputation: 24208
Hi and thanks for looking!
I have a workflow that constructs a set of dictionaries, each with identical KEYS, but (of course) various VALUES. After these dictionaries are constructed, they are added to a common list. I need to order that list based on a particular KEY in each dictionary.
I am using C#, .NET 4, LINQ, Lambdas, etc.
How do I order a list of dictionaries based on a common key property in each dictionary? For example if I have the code below, how do I order based on the "Color" key?
IDictionary<String, object> item1 = new Dictionary<String, object>{"Color","Red"};
IDictionary<String, object> item2 = new Dictionary<String, object>{"Color","Blue"};
IDictionary<String, object> item3 = new Dictionary<String, object>{"Color","Green"};
var dictionaryList = new List<IDictionary<String, object>>();
dictionaryList.add(item1);
dictionaryList.add(item2);
dictionaryList.add(item3);
var orderedList = dictionaryList.OrderBy[??????];
Thanks!
Upvotes: 1
Views: 479
Reputation: 41757
You need to pass the OrderBy method a function that given a Dictionary<String, object>
returns the item you wish to order by, so:
var orderedList = dictionaryList.OrderBy(d => d["Color"]);
Will suffice.
As an aside, you can clean up the initialisation a little bit like so:
var orderedList = new[] { item1, item2, item3 }.OrderBy(d => d["Color"]);
Upvotes: 4
Reputation: 51329
Unless I am missing something?
var orderedList = dictionaryList.OrderBy(d => d["Color"]);
Upvotes: 4