Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I order a Dictionary<string,string> by a substring within the value?

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?

like image 483
justJ Avatar asked Jan 15 '23 04:01

justJ


1 Answers

var ordered = unordered.OrderBy(x => x.Value.Split(':').Last())
                       .ToDictionary(x => x.Key, x => x.Value);
like image 90
L.B Avatar answered Jan 29 '23 20:01

L.B