I have this list :
List<Dictionary<int, string>> list = new List<Dictionary<int, string>>();
and I'd like to order it (ascending) based on Dictionary int value. How can I do it?
Example :
Dictionary<int, string> Min1 = new Dictionary<int, string>();
Dictionary<int, string> Min2 = new Dictionary<int, string>();
Dictionary<int, string> Min3 = new Dictionary<int, string>();
Dictionary<int, string> Min4 = new Dictionary<int, string>();
Dictionary<int, string> Min5 = new Dictionary<int, string>();
Min1.Add(3, "name");
Min2.Add(1, "hello");
Min3.Add(5, "marco");
Min4.Add(4, "is");
Min5.Add(2, "my");
List<Dictionary<int, string>> list = new List<Dictionary<int, string>>();
list.Add(Min1);
list.Add(Min2);
list.Add(Min3);
list.Add(Min4);
list.Add(Min5);
// NOW I NEED TO ORDER list BASED ON DICTIONARY INT VALUE
// SO THE ORDER ON THE LIST SHOULD BE Min2, Min5, Min1, Min4, Min3
I'd like to sort the list, so when I cycle it and I get to the string I print "hello my name is marco"
if you want to flatten data and sort them you can try this:
list.SelectMany(x=>x).OrderBy(x=>x.Key)
but if you don't like flatten data and just sort dictionaries you can do:
list.Select(x=>x.OrderBy(y=>y.Key));
Edit: As I understand you just need use one dictionary, so you can do this:
Dictionary<int,string> dic = new Dictionary<int,string>();
var result = dic.OrderBy(x=>x.Key).ToLookup(x=>x);
If you want use List instead of dictionary (in your case seems is not good) you can do this;
List<KeyValuePair<int,string>> lst1 = new List<KeyValuePair<int,string>>();
var result = lst1.OrderBy(x=>x.Key).ToLookup(x=>x);
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