Reputation: 145
in my C# program I have a list, which I populate with Dictionary elements:
List<Dictionary<string, object>> mylist = new List<Dictionary<string, object>>();
Dictionary<string, object> d1 = new Dictionary<string, object>();
d1.Add("val1", 1);
d1.Add("val2", 2);
d1.Add("val3", 3);
mylist.Add(d1);
Dictionary<string, object> d2 = new Dictionary<string, object>();
d2.Add("val1", 4);
d2.Add("val2", 5);
d2.Add("val3", 6);
mylist.Add(d2);
Dictionary<string, object> d3 = new Dictionary<string, object>();
d3.Add("val1", 7);
d3.Add("val2", 8);
d3.Add("val3", 9);
mylist.Add(d3);
I would like to sort the list according to a certain element in the dictionary elements, e.g., sort the list according to the "val3" object in the dictionaries. I tried this: mylist.OrderBy(x => x["val3"]); My list order was still the same. Any idea what I did wrong? Thanks
Upvotes: 0
Views: 103
Reputation: 101732
Probably you haven't assigned the result that OrdeyBy
returns. You can do:
mylist = mylist.OrderBy(x => x["val3"]).ToList();
This will order your elements, put them into a new list.
You can also do that without creating a new list, using List<T>.Sort
method:
mylist.Sort((x,y) => ((IComparable)x["val3"]).CompareTo(y["val3"]));
Upvotes: 3