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, // 現在の生徒より点数が良い生徒の人数 + 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 に落としんだ。