【问题标题】:Find the maximum of the object array找到对象数组的最大值
【发布时间】:2018-04-02 11:15:47
【问题描述】:

所以我想找一个学校班里最年长的人。年龄是根据他的个人密码计算的。例如,120499-12345,其中第一部分是日期,“-”后面的第一个数字可以是 1 或 2,取决于人的出生时间(2000 年之前 - “1”,2000 年之后 - “2”) .个人代码是字符串类型,我使用子字符串从代码中获取年份,并使用 1 或 2 来计算年龄。问题是我真的不明白如何找到最年长的人。

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

                    }


                }    
        }

【问题讨论】:

  • 所以120499-12345 的意思是这个人出生于 1999 年 12 月 4 日?
  • year 在您的代码中始终为零!用一个完整的例子说明如何获取字符串代码的年龄!
  • 我假设“gads”在某些语言中的意思是“年龄”,我们看到翻译不完整。
  • 对我来说毫无意义。你为什么选择99?职业训练局
  • 120499 是日期。这个日期有什么意义?如果没有明确描述您如何从 120499 到某个年龄,没有人可以帮助您。

标签: c# arrays object


【解决方案1】:

我不太明白如何找到最年长的人

当然,您的方法中发生了太多事情。您可以采取不同的方法并首先改进总体设计,而不是尝试修复它。


您可以将您的 i'm-responsible-for-everything 方法拆分为单一重点功能:

DateTime GetBirthDate(string personCode) { ... }

TimeSpan GetAge(DateTime birthDate) { ... }

现在你可以单独测试这个逻辑了。

仔细想想,Student 似乎有责任知道自己的年龄。

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) { ... }
}

然后您可以将简单且可测试的构建块组装成更大的解决方案

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

一切都变得更加清晰,更不用说我们现在能够轻松找到其他统计数据——平均年龄、前 10 名最年轻的学生等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 2018-04-08
    • 2022-01-12
    相关资源
    最近更新 更多