Ranking items in a list with linq
I am trying to figure out a way to rank items in a list, and hold the results in an object or another list. I know about the orderby method, but I don't exactly know how to go about creating a corresponding rank number for each item. Is this possible with linq? For example:
List numbers = new List();
numbers.Add(650);
numbers.Add(150);
numbers.Add(500);
numbers.Add(200);
and then store the results from either low to high or high to low here:
public class NumberRank
{
public int Number {get; set;}
public int Rank {get; set;}
public NumberRank(int number)
{
Number = number;
Rank = ????????;
}
}
Thanks, in advance.
VulpesPosted Mar 14, 2012, 7:19 AM
using System;
using System.Collections.Generic;
using System.Linq;
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
numbers.Add(650);
numbers.Add(150);
numbers.Add(500);
numbers.Add(200);
List
// check it worked
foreach(NumberRank nr in numberRanks) Console.WriteLine("{0} : {1}", nr.Rank, nr.Number);
Console.ReadKey();
}
}
To rank in ascending order (i.e. lowest number first), then just replace OrderByDescending by OrderBy.
RichPosted Mar 15, 2012, 2:38 AM