勇哥注:
去除List的重复元素的问题是比较常见的需求,C#有标准的做法,以后不要自己写了。
public class Student
{
public string Name { get; private set; }
public int Id { get; private set; }
public string Hobby { get; private set; }
public Student(string name, int id, string hobby)
{
this.Name = name;
this.Id = id;
this.Hobby = hobby;
}
/// <summary>
/// 方便输出,重写ToString方法
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("{0}\t{1}\t{2}", this.Name, this.Id, this.Hobby);
}
}
public class Compare : IEqualityComparer<Student>
{
public bool Equals(Student x, Student y)
{
return x.Id == y.Id;//可以自定义去重规则,此处将Id相同的就作为重复记录,不管学生的爱好是什么
}
public int GetHashCode(Student obj)
{
return obj.Id.GetHashCode();
}
}