How can I order a dictionary <string, string> by a substring inside a value?

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

I would like to order a dictionary by the last substring (Smith) in ascending order and, preferably, as follows:

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

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

+4
source share
3 answers
 var ordered = unordered.OrderBy(x => x.Value.Split(':').Last()) .ToDictionary(x => x.Key, x => x.Value); 
+6
source

Try

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

Take a look at the IDictionary method, namely http://msdn.microsoft.com/en-us/library/bb549422.aspx , noting the comparer parameter. This should point you in the right direction, and I think you will find a study of the remaining benefits.

+1
source

Source: https://habr.com/ru/post/1443093/


All Articles