use*_*652 5 c# linq sql-server ranking rank
例如,在数据库(SQL Server)中,一列值如下:
Col1
====
10
5
15
20
5
10
2
Run Code Online (Sandbox Code Playgroud)
这就像整数数据列表.
排名应该是:
Col1 Rank
==== ====
20 1
15 2
10 3
10 3
5 4
5 4
2 5
Run Code Online (Sandbox Code Playgroud)
我试过以下方式:
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
Run Code Online (Sandbox Code Playgroud)
但它只有在数据是唯一的情况下才有效.当索引返回时,当多个行中存在相同的"Col1"值时,它会失败0, 1, 2, 3, 4, 5, 6.
如何使用C#LINQ列出包含不同的数据(在大多数情况下!)时的排名?
为什么不在数据库中这样做?
SELECT [Col1], DENSE_RANK() OVER (ORDER BY Col1 DESC) AS [Rank]
FROM Table
Run Code Online (Sandbox Code Playgroud)
但如果你必须在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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6229 次 |
| 最近记录: |