我的代码看起来像那样。看一看。
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)
{
}
}
}
看看我离开时的评论。如何扫描学生的生日?如何编写一种从所有学生中找到最老的方法?我还应该更改日期格式吗?
也许我应该删除日期中的点?或者我该怎么做才能做得更好?
我将格式更改为YYYY-MM-DD。现在怎么办 ?好吗?
public DateTime Birthday { get; set; }
使用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” - 上面将评估为false
。所以我会进一步修改它来阅读
bool freshman = (values[6].ToLower() == "fuksas")
排序
尝试类似的东西
List<Student> sortedList = students.OrderByDescending(s => s.DoB).ToList();
然后抓住列表中的第一个条目。
其他问题
正如评论中所述,如果任何人有一个带有空格的名字或姓氏,你将遇到问题 - 它会抛出其他所有的顺序。
为了解决这个问题,我实际上将csv
(逗号分隔值)作为您的文件格式 - 在空格上分割字符串对于名字和姓氏来说不是一个好主意。
我将告诉你如何手动找到最旧的一个(只是为了看你的工作原理):
public DateTime GetOldestBirthDate()
{
DateTime birthDate = DateTime.Now;
foreach (var item in List<Student>)
{
if (birthDate < item.birthDate)
birthDate = item.birthDate;
}
return birthDate;
}
但是,有很多方法可以做到这一点,例如:参见Linq。
我希望我帮助过你。