我想根據年齡排序列表中的姓名(迄今爲止我已經完成),但是我想知道如何才能再按這些姓名排序打印到新文件之前的姓氏。例如,如果我有5個20歲不同姓氏的人,我怎麼能確保這5個人按照字母順序升序?對姓名列表進行排序,並輸入姓名和年齡C#
class Person : IComparable
{
string vorname;
string nachname;
int age;
public Person(string vorname, string nachname, int age)
{
this.age = age;
this.nachname = nachname;
this.vorname = vorname;
}
public int CompareTo(object obj)
{
Person other = (Person)obj;
int a = this.age - other.age;
if (a != 0)
{
return -a;
}
else
{
return age.CompareTo(other.age);
}
}
public override string ToString()
{
return vorname + " " + nachname + "\t" + age;
}
}
class Program
{
static void Main(string[] args)
{
Person[] peeps = new Person[20];
try
{
StreamReader sr = new StreamReader("inputNames.txt");
int count = 0;
while (!sr.EndOfStream)
{
string data = sr.ReadLine();
Console.WriteLine();
string[] info = data.Split(',');
peeps[count] = new Person(info[0], info[1], int.Parse(info[2]));
count++;
}
Array.Sort(peeps);
sr.Close();
}
catch(FileNotFoundException e)
{
Console.WriteLine(e.Message);
}
StreamWriter sw = new StreamWriter("outputNames.txt");
Console.WriteLine();
foreach (Person p in peeps)
{
Console.WriteLine(p);
sw.WriteLine(p);
}
sw.Close();
}
}
編輯*沒有LINQ,我必須使用IComparable。 –