-1

学生のスコアを含む単純な POCO クラスがあります。

For example:
Math - 83%
Engrish - 82%
Chemistry - 81%
Drama - 100%
etc..

スコアで並べ替えられた上位 3 つのプロパティを把握できる( LINQを使用して?) 方法はありますか?

最終的なオブジェクトは、2 つのフィールドを持つ匿名型の IList<T> になると想定しています。

  1. お名前(物件名)
  2. スコア (小数値)。

ただし、オブジェクト内のプロパティの数は有限です:)

助言がありますか?

別の答えとして、代わりにデータベースでこれを行うことはできますか?

4

4 に答える 4

3

このようなものをお探しですか?

class Notes
{
    public double Math{ get; set; }
    public double English { get; set; }
    public double Chemistry { get; set; }
    public double Drama { get; set; }
    public string IgnoreMePlease { get; set; }
}

class Program
{
    static void PrintHighestNotes(Notes notes)
    {
        var pairs = from property in notes.GetType().GetProperties()
                     where property.PropertyType == typeof (double)
                     select new
                            {
                                Name = property.Name,
                                Value = (double) property.GetValue(notes, null)
                            };
        var result = pairs.OrderByDescending(pair => pair.Value);

        foreach (var pair in result)
            Console.WriteLine("{0} = {1}", pair.Name, pair.Value);
    }

    static void Main(string[] args)
    {
        Notes notes = new Notes()
                      {
                          Chemistry = 0.10,
                          Math = 0.2,
                          Drama = 1,
                          English = 0.3,
                          IgnoreMePlease = "Ignore"
                      };
        PrintHighestNotes(notes);
    }
}
于 2009-07-30T07:14:11.327 に答える
1

すべてのデータが既にメモリ内にある場合を除き、データベースに正しいデータを選択させる方が効率的です。

成績をフィールドとしてデータベースに保存する場合は、クエリを実行できるように正規化する必要があります。最良の方法は、データベースを再設計し、成績を別のテーブルの行として配置することです。データは、フィールド名としてではなく、テーブルのフィールドにある必要があります。

select top 3 GradeName, Grade
from Grades
where StudentId = 42
order by Grade desc

その場でデータを正規化することもできますが、もちろんそれはほとんど効率的ではありません。

select top 3 GradeName, Grade
from (
   select GradeName = 'Engrish', Grade = Engrish from Students where StudentId = 42
   union all
   select 'Drama', Drama from Students where StudentId = 42
   union all
   select 'Math', Math from Students where StudentId = 42
   union all
   select 'Chemistry', Chemistry from Students where StudentId = 42
) Grades
order by Grade desc
于 2009-07-30T07:27:38.337 に答える
1

件名をキー、スコアを値として辞書を使用する方が簡単です。

Dictionary<string, int> scores = new Dictionary<string, int>();
...

var top3Subjects = (from s in scores
                    orderby s.Value descending
                    select s).Take(3);

IEnumerable<KeyValuePair<string, int>>これは、次のように使用できる を返します。

foreach (var s in top3Subjects)
{
    Console.WriteLine("{0} : {1}", s.Key, s.Value);
}
于 2009-07-30T07:51:45.900 に答える
0

あなたの質問では、スコアがすべて個別のプロパティなのか、それともある種のリストなのかが明確ではありません。それらがリストの場合、これは機能します:

 var topScores =
    (from s in Scores
    orderby s.Score descending
    select new { s.Name, s.Score}).Take(3);
于 2009-07-30T07:14:34.243 に答える