1

Given a

List<string> s=new List<string>{"a","b","c"}
and 
List<double> srank=new List<double>{2,3,1}

I wish to sort s by the number of srank in descending order i.e. after sorting

s={"b","a","c"}

what's the easiest way for doing this?

william007
  • 17,375
  • 25
  • 118
  • 194

2 Answers2

9

Try this

   var sorted = s
      .Zip(srank, (x,y) => new { s = x, rank = y })
      .OrderByDescending(x => x.rank)
      .Select(x => x.s)
      .ToList();

Read more about Zip

Read more about OrderByDescending

EDIT:

There is a very short solution using arrays: if s and srank were Arrays we can do this:

Array.Sort(srank,s);
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
1

If I were you I'd use a List<Tuple> a Dictionary or create a new class then do

var dictionary = new Dictionary<string, double>
{
    { "a", 2 },
    { "b", 3 },
    { "c", 1 }
};

var result = dictionary.OrderByDescending(d => d.Value).Select(d => d.Key);
dav_i
  • 27,509
  • 17
  • 104
  • 136