【发布时间】:2016-11-15 00:29:28
【问题描述】:
我想首先按年龄对列表中的姓名进行排序(到目前为止我已经这样做了),但我想知道如何在打印到新文件之前再次按姓氏对这些姓名进行排序。例如,如果我有 5 个 20 岁的不同姓氏的人,我如何确保这 5 个人按字母升序排列?
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();
}
}
【问题讨论】:
-
EDIT* 没有 linq,我必须使用 IComparable。
标签: c# sorting icomparable