gpt4 book ai didi

c# - 如何从整数列表中计算排名?

转载 作者:太空狗 更新时间:2023-10-29 22:59:45 26 4
gpt4 key购买 nike

例如,在数据库(SQL Server)中,一列值如下:

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

这就像整数数据列表。

排名应该是:

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

我试过以下方式:

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

但它只有在数据是唯一的情况下才有效。当索引返回 0, 1, 2, 3, 4, 5, 6 时,当多个行中存在相同的“Col1”值时,它会失败。

如何使用 C# LINQ 计算列表中包含不明确(在大多数情况下!)的数据时的排名?

最佳答案

为什么不在数据库中做呢?

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

但是如果你必须用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();

关于c# - 如何从整数列表中计算排名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19493658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com