Domanda

I have a Dictionary <string, string> where the value is a concatenation of substrings delimited with a :. For example, 123:456:Bob:Smith.

I would like to order the dictionary by the last substring (Smith) ascending, and preferably like this:

orderedDictionary = unordered
                        .OrderBy(x => x.Value)
                        .ToDictionary(x => x.Key, x => x.Value);

So, I need to somehow treat the x.Value as a string and sort by extracting the fourth substring. Any ideas?

È stato utile?

Soluzione

var ordered = unordered.OrderBy(x => x.Value.Split(':').Last())
                       .ToDictionary(x => x.Key, x => x.Value);

Altri suggerimenti

Try

orderedDictionary = unordered.OrderBy(x => x.Value.Substring(x.Value.LastIndexOf(":"))).ToDictionary(x => x.Key, x => x.Value);

Take a look at the OrderBy Method of IDictionary, specifically this one http://msdn.microsoft.com/en-us/library/bb549422.aspx noting the comparerparameter. That should point you in the right direction and I think you'll find learning the remainder of benefit.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top