Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate rank from list of integer?

In database(SQL Server), say, one column values are like:

Col1
====
10
5
15
20
5
10
2

This is like list of integer data.

Rank should be:

Col1 Rank
==== ====
20    1
15    2
10    3
10    3
5     4
5     4
2     5

I have tried in following manner:

1) First sort the list of data in descending order of "Col1" value
2) Find the index of a particular record using FindIndex() method.
3) Then Rank = Index + 1

But it will only work if the data are unique. It fails when same "Col1" values are present in multiple rows as the index is returning 0, 1, 2, 3, 4, 5, 6.

How to calculate the rank when the list contains data which are not distinct(in most cases!) using C# LINQ?

like image 399
user2338652 Avatar asked Oct 21 '13 11:10

user2338652


People also ask

How do you rank a list of values?

In descending order, the higher score is given the numerically lower rank. For example, if you have bowling scores of {150, 125, 180, 175}, the value 180, the highest value in the list, is given a rank of 1 and the value 125, the lowest value in the list, is given the rank of 4.

How do you find the rank of an array?

Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Property Value: It returns the rank (number of dimensions) of the Array of type System.

How do I calculate rank in Excel?

=RANK(number,ref,[order]) The RANK function uses the following arguments: Number (required argument) – This is the value for which we need to find the rank. Ref (required argument) – Can be a list of, or an array of, or reference to, numbers.

How does Python calculate rank?

rank() function compute numerical data ranks (1 through n) along axis. Equal values are assigned a rank that is the average of the ranks of those values. Example #1: Use Series. rank() function to rank the underlying data of the given Series object.


1 Answers

Why not do it in the database?

SELECT [Col1], DENSE_RANK() OVER (ORDER BY Col1 DESC) AS [Rank]
FROM Table

But if you must do it in C#

var data = new List<int>();
var rankings = data.OrderByDescending(x => x)
                   .GroupBy(x => x)
                   .SelectMany((g, i) =>
                       g.Select(e => new { Col1 = e, Rank = i + 1 }))
                   .ToList();
like image 114
Dustin Kingen Avatar answered Nov 09 '22 10:11

Dustin Kingen