c# how to scan members date and how to find the oldest one?

时间:2018-09-18 20:03:25

标签: c#

my code looks like that. Take a look.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace U1_15
{
class Student
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    //What should i use for a date??                    /// ///    ///
    public int StudId { get; set; }
    public int Course { get; set; }
    public int MobileNumber { get; set; }
    public bool Freshman { get; set; }
}
class Program
{
    List<Student> ReadFile()
    {
        List<Student> students = new List<Student>();
        string[] lines = File.ReadAllLines(@"studentai.txt");
        foreach (string line in lines)
        {
            string[] values = line.Split(' ');
            string lastname = values[0];
            string firstname = values[1];
            //Date!!!???                          ///////////////////
            int studid = int.Parse(values[3]);
            int course = int.Parse(values[4]);
            int mobilenumber = int.Parse(values[5]);
            bool freshman;
            if (values[6] == "Fuksas")
            {
                freshman = true;
            }
            else
                freshman = false;
        }
        return students;
    }
    static void Main(string[] args)
    {
    }
}
}

I have this data on file. file

Take a look at comments where i left. How to scan student's birthdate? And how to write a method that finds from all students the oldest one ? Also should i change date format ?

Maybe i should delete dots in date ? Or what should i do to make better ?

I changed format to YYYY-MM-DD. What now ? Is it good?

   public DateTime Birthday { get; set; } 

2 个答案:

答案 0 :(得分:1)

使用DateTime作为日期:

public DateTime DoB { get; set; }

从文本文件中读取日期:

DateTime dob = DateTime.Parse(values[2]);

这似乎适合您的情况,但是如果您对提供的数据文件有任何控制权,我肯定会更改提供的日期格式。

您应该查看的其他内容。

首先,这个

    bool freshman;
    if (values[6] == "Fuksas")
    {
        freshman = true;
    }
    else
        freshman = false;

可以简化为

bool freshman = (values[6] == "Fuksas");

但是,如果“ Fuksas” 的大小写因任何原因而有所不同-例如,有人写了“ fuksas” ,则-以上内容将评估为{{ 1}}。 因此,我将其进一步修改为

false

排序

尝试类似

bool freshman = (values[6].ToLower() == "fuksas")

,然后获取列表中的第一项。

其他问题

如评论中所述,如果任何人的名字或姓氏中有空格,您将遇到问题-它将把其他所有东西都排掉。

为了解决这个问题,我会改用List<Student> sortedList = students.OrderByDescending(s => s.DoB).ToList(); (用逗号分隔的值)作为您的文件格式-用空格分隔字符串不是一个好名字和姓氏的好主意。

答案 1 :(得分:0)

I'll show you how find the oldest one manually (just to you see how works):

public DateTime GetOldestBirthDate()
{
    DateTime birthDate = DateTime.Now;

    foreach (var item in List<Student>)
    {
         if (birthDate < item.birthDate)             
                birthDate = item.birthDate;
    }

    return birthDate;
}

But, there are many ways to do this, for example: see Linq.

I hope I helped you.