Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a simple POCO class that contains the student's scores.

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

Is there a way (using LINQ?) that I could figure out the top 3 properties ordered by score?

I'm assuming the final object will be an IList<T> of an anonymous type, which will have two fields.

  1. Name (the name of the property)
  2. Score (the decimal value).

The number of properties in the object ARE finite though :)

Any suggestions?

As an alternative answer, could this be done in a database instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
140 views
Welcome To Ask or Share your Answers For Others

1 Answer

Are you looking for something like this?

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...