Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

.net - Trying to find the top 3 properties of a POCO instance

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...