Matt Cashatt
Matt Cashatt

Reputation: 24208

How do I order results of a List<IDictionary> object using Linq?

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!

Upvotes: 1

Views: 479

Answers (3)

Rich O&#39;Kelly
Rich O&#39;Kelly

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

Chris Shain
Chris Shain

Reputation: 51329

Unless I am missing something?

var orderedList = dictionaryList.OrderBy(d => d["Color"]);

Upvotes: 4

SLaks
SLaks

Reputation: 887453

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

Upvotes: 2

Related Questions