我试图想出一种方法来对列表中的项进行排名,并将结果保存在对象或其他列表中。我知道orderby方法,但我不知道如何为每个项目创建相应的排名。
例如:
List<int> numbers = new List<int>();
numbers.Add(650);
numbers.Add(150);
numbers.Add(500);
numbers.Add(200);
然后将结果从低到高或高到低存储在这里:
public class NumberRank
{
public int Number {get; set;}
public int Rank {get; set;}
public NumberRank(int number)
{
Number = number;
Rank = ????????;
}
}
通过LINQ的任何解决方案?
答案 0 :(得分:17)
Select扩展方法的一个重载返回索引:
通过合并元素的索引,将序列的每个元素投影到新的表单中。
您可以使用它来获得排名:
public class NumberRank
{
public int Number {get; set;}
public int Rank {get; set;}
public NumberRank(int number, int rank)
{
Number = number;
Rank = rank;
}
}
List<int> numbers = new List();
numbers.Add(650);
numbers.Add(150);
numbers.Add(500);
numbers.Add(200);
numbers.OrderBy(n => n)
.Select((n, index) => new NumberRank(n, index));
答案 1 :(得分:12)
这应该这样做:
public class NumberRank
{
public int Number {get; set;}
public int Rank {get; set;}
public NumberRank(int number, int rank)
{
Number = number;
Rank = rank;
}
}
class Test
{
static void Main()
{
List<int> numbers = new List<int>();
numbers.Add(650);
numbers.Add(150);
numbers.Add(500);
numbers.Add(200);
List<NumberRank> numberRanks = numbers.OrderByDescending(n => n).Select((n, i) => new NumberRank(n, i + 1)).ToList();
// check it worked
foreach(NumberRank nr in numberRanks) Console.WriteLine("{0} : {1}", nr.Rank, nr.Number);
Console.ReadKey();
}
}
按升序排列(即最低编号),然后只需用OrderBy替换OrderByDescending。
答案 2 :(得分:1)
Function Rank(Of T As IComparable)(list As IEnumerable(Of T), item As T) As Integer
Return list.Count(Function(x) x.CompareTo(item) < 0) + 1
End Function
Public Sub Main()
Dim l = New Integer() {9, 1, 3, 8, 4, 6}
Console.WriteLine("6 is the " & Rank(l,6) & "th element of ")
Console.WriteLine([String].Join(" ", l))
End Sub
6 is the 4th element of
9 1 3 8 4 6
中