简体   繁体   中英

Find the maximum of the object array

So I want to find the oldest person in a school class. The age is calculated according to his personal code. For example, 120499-12345, where the first part is the date and the first number after the "-" can be 1 or 2,depending on when did person born(before 2000 - "1", after 2000 - "2"). Personal code is a string type and I used substrings to get the year from code and the 1 or 2 to calculate the age. And the problem is that I don't really understand how to find the oldest person.

        public void Oldest()
        {

            int age = 0;

                foreach (Student b in students)// students is an array of Student class
                {
                    string sub1 = b.pers_code.Substring(4, 2);
                    string sub2 = b.pers_code.Substring(7, 1);
                    int type = 0;
                    type = Convert.ToInt32(sub2);
                    int year = 0;
                    year = Convert.ToInt32(sub1);




                    if (type == 2)
                    {
                        age = 18 - year;


                    }

                    else
                    {
                        age = 2018 - (year + 1900);

                    }


                }    
        }

I don't really understand how to find the oldest person

Sure, there is too much going on in your method. Instead of trying to fix it, you can take a different approach and improve the general design first.


You can split your i'm-responsible-for-everything method into single-focused functions:

DateTime GetBirthDate(string personCode) { ... }

TimeSpan GetAge(DateTime birthDate) { ... }

Now you can test this logic separately.

Come to think of it, it actually seems the Student 's responsibility to know his or her age.

class Student
{
    ...
    // instead of computing, you can set these once in the constructor
    public DateTime BirthDay => GetBirthDay(this.PersonalCode);
    public TimeSpan Age => GetAge(this.BirthDay);
    ...
    private TimeSpan GetAge(DateTime birthDate) { ... }
}

And then you can assemble your simple and testable building blocks into a larger solution

var oldest = students.OrderByDescending(s => s.Age).FirstOrDefault();
var maxAge = students.Max(s => s.Age);

It all got much clearer, not to mention that we're now able to easily find other stats -- average age, top-10 youngest students etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM