LINQ でランキングを作成するサンプルを書いてみた。
using System;
using System.Linq;
namespace LinqRankingSample
{
class Student
{
public string Name { get; set; }
public int Score { get; set; }
}
class Program
{
static void Main(string[] args)
{
var students = new Student[]
{
new Student()
{
Name = "香川",
Score = 70,
},
new Student()
{
Name = "本田",
Score = 85,
},
new Student()
{
Name = "柴崎",
Score = 70,
},
new Student()
{
Name = "宇佐美",
Score = 80,
},
new Student()
{
Name = "長友",
Score = 60,
},
new Student()
{
Name = "岡崎",
Score = 65,
},
};
var ranking = from s1 in students
let higher = from s2 in students
where s2.Score > s1.Score
select s2
select new
{
s1.Name,
s1.Score,
Rank = higher.Count() + 1,
} into s3
orderby s3.Rank
select s3;
foreach(var student in ranking)
{
Console.WriteLine("{0} 位 {1} {2} 点", student.Rank, student.Name, student.Score);
}
Console.ReadLine();
}
}
}
ある生徒の順位は、「その生徒よりも点数が高い生徒の人数 + 1」で求めることができるので、
それを LINQ に落としんだ。