泛型排序 问题
问题如下
现要对一组数据(name,age,score)进行排序处理,并分别对age,score进行排序
public class Person : IComparable<Person>
{
string name;
int age;
int score;
public Person(string s, int i,int sc)
{
name = s;
age = i;
score = sc;
}
public int CompareTo(Person p)
{
return age - p.age;//现在可以对age进行排序,下一句对score排序,但无法调用
// return score - p.score;
}
public override string ToString()
{
return name + ":" + age+" scroe:"+score;
}
public bool Equals(Person p)
{
return (this.age == p.age || this.score==p.score);
}
}
// 尖括号中的类型参数 T。
public class MyList<T> : IEnumerable<T>
{
protected Node head;
protected Node current = null;
protected class Node
{
public Node next;
private T data;
public Node(T t)
{
next = null;
data = t;
}
public Node Next
{
get { return next; }
set { next = value; }
}
public T Data
{
get { return data; }
set { data = value; }
}
}
public MyList()
{
head = null;
}
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
}
public IEnumerator<T> GetEnumerator()
{
Node current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class SortedList<T> : MyList<T> where T : IComparable<T>
{
public void BubbleSort()
{
if (null == head || null == head.Next)
return;
bool swapped;
do
{
Node previous = null;
Node current = head;
swapped = false;
while (current.next != null)
{
if (current.Data.CompareTo(current.next.Data) > 0)
{
Node tmp = current.next;
current.next = current.next.next;
tmp.next = current;
if (previous == null)
{
head = tmp;
}
else
{
previous.next = tmp;
}
previous = tmp;
swapped = true;
}
else
{
previous = current;
current = current.next;
}
}// 结束 while
} while (swapped);
}
}
static void Main(string[] args)
{
SortedList<Person> list = new SortedList<Person>();
string[] names = new string[] { "Franscoise", "Bill", "Li", "Sandra", "Gunnar", "Alok", "Hiroyuki", "Maria", "Alessandro", "Raul" };
int[] ages = new int[] { 45, 19, 28, 23, 18, 9, 108, 72, 30, 35 };
int[] scores = new int[] { 90, 40, 28, 23, 18, 56, 108, 44, 30, 23 };
for (int x = 0; x < names.Length; x++)
{
list.AddHead(new Person(names[x], ages[x],scores[x]));
}
// 对列表进行排序。
list.BubbleSort();
}