当我尝试使用 .NET 2.0 从 List 中删除重复项时,我无法获得预期的结果。
List<Student> list1 = new List<Student>();
Student s = new Student();
s.Age = "35";
s.Name = "Nazmul";
list1.Add(s);
s = new Student();
s.Age = "35";
s.Name = "Nazmul";
list1.Add(s);
s = new Student();
s.Age = "35";
s.Name = "Nazmul";
list1.Add(s);
s = new Student();
s.Age = "35";
s.Name = "Nazmul";
list1.Add(s);
IComparer<Student> compare = new MyOrderingClass();
list1.Sort(compare);
Int32 index = 0;
while (index < list1.Count - 1)
{
if (list1[index].Equals(list1[index + 1]))
{
list1.RemoveAt(index);
}
else
{
index++;
}
}
foreach (Student st in list1)
{
Response.Write("Name:" + st.Name);
Response.Write("Age:" + st.Age + "<br/>");
}
上面使用的类和方法如下:
public class Student
{
private String name;
private String age;
public String Name
{
get { return name; }
set { name = value; }
}
public String Age {
get { return age; }
set { age = value; }
}
}
public class MyOrderingClass : IComparer<Student>
{
public int Compare(Student x, Student y)
{
int compareName = x.Name.CompareTo(y.Name);
if (compareName == 0)
{
return x.Age.CompareTo(y.Age);
}
return compareName;
}
}
我将所有列表项作为输出。想知道我在哪里做错了。