user4575494
user4575494

Reputation:

How can i Sort a List<Tuple<int, double>>

Hello and thanks for reading this post.

I have a list that is created this way

List<Tuple<int, double>> Ratings = new List<Tuple<int, double>>();

Lets say the value of the list is as below

Index      int     double

[0]        1       4,5
[1]        4       1,0
[2]        3       5,0
[3]        2       2,5

How can I sort the list so the double value that is higgest is on top? like this

Index      int     double
[0]        3       5,0
[1]        1       4,5
[2]        2       2,5
[3]        4       1,0

Upvotes: 8

Views: 7363

Answers (5)

Denis
Denis

Reputation: 6082

var comparer = Comparer<Tuple<int, double>>.Create((x, y) => -1 * x.Item2.CompareTo(y.Item2));
Ratings.Sort(comparer);

Upvotes: 0

Lokesh B R
Lokesh B R

Reputation: 282

List<Tuple<int, double>> Ratings = new List<Tuple<int, double>>();

                    Ratings.Add(new Tuple<int, double>(1, 4.5));
                    Ratings.Add(new Tuple<int, double>(4, 1.0));
                    Ratings.Add(new Tuple<int, double>(3, 5.0));
                    Ratings.Add(new Tuple<int, double>(2, 2.5));

                    var list = Ratings.OrderByDescending(c => c.Item2).ToList();

Upvotes: 3

Mike Tsayper
Mike Tsayper

Reputation: 1802

Ratings.OrderByDescending(t => t.Item2);

Upvotes: 10

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

Have you tried using the Sort method on the list, intellisense should have suggested it to you and it's kinda natural:

Ratings.Sort((x, y) => y.Item2.CompareTo(x.Item2));
// at this stage the Ratings list will be sorted as desired

Upvotes: 4

Satpal
Satpal

Reputation: 133403

You can simply use

Ratings = Ratings.OrderByDescending (t => t.Item2).ToList();

Upvotes: 11

Related Questions