Sort Descending

I have

List<string> strs; double[] values; 

where the array of values ​​contains the value of each line in the strs list

Say strs={"abc","def","ghi"} and values={3,1,2} this means that "abc" has a value of 3, etc.

I want to sort strs and values ​​sorted by values ​​so that it becomes

 strs={"def","ghi","abc"} values={3,2,1} 

I use

 string[] strsArr = strs.ToArray(); Array.Sort(values, strsArr);//1. sort it ascendingly strs = strsArr.ToList(); Array.Reverse(strs);//2. reverse it 

Is there a way to sort it in a descending order directly without two phases?

+4
source share
3 answers

You can use the dictionary and Linq to solve this problem.

 var dict = new Dictionary<string, double>() { {"abc",3}, {"def",1}, {"ghi",2} }; var sorted = dict.OrderByDescending(g => g.Value) .Select(g => g.Key) .ToArray(); 

Please note that if you do not have ToArray () at the end, the sort will be delayed until subsequent listing and may be accidentally listed several times.

+3
source

How about this:

 var strs = new [] { "abc", "def", "ghi", }; var values = new [] { 3, 1, 2, }; strs = strs .Zip(values, (s, v) => new { s, v }) .OrderByDescending(sv => sv.v) .Select(sv => sv.s) .ToArray(); 
+2
source

try using a dictionary:

 Dictionary<string, double> dictionary = new Dictionary<string, double>(); dictionary.Add("abc", 3); dictionary.Add("def", 1); dictionary.Add("ghi", 2); var sortedDict = dictionary.OrderByDescending(x => x.Value); double[] values = sortedDict.Select(x => x.Value).ToArray(); List<string> strs = sortedDict.Select(x => x.Key).ToList(); 
0
source

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


All Articles