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?
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.
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.
=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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With