1

Hi and thanks for looking!

Background

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.

Question

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!

Community
  • 1
  • 1
Matt Cashatt
  • 23,490
  • 28
  • 78
  • 111
  • You could instead use a [`List`](http://msdn.microsoft.com/en-us/library/system.tuple.aspx) or [Dictionary with Tuples as key](http://stackoverflow.com/a/956043/284240). – Tim Schmelter Feb 14 '12 at 17:42

3 Answers3

4

Unless I am missing something?

var orderedList = dictionaryList.OrderBy(d => d["Color"]);
Chris Shain
  • 50,833
  • 6
  • 93
  • 125
4

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"]);
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
2

You're looking for d => d["Color"].

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964