C#Collection/List - 唯一ID

Rob*_*lin 2 c# list

在C#中,我正在尝试创建一个对象列表,当一个新的东西被添加到列表中时,会检查它以确保不使用相同的ID.我在Linq有解决方案但是我试图在没有linq的情况下做到这一点.

public void AddStudent(Student student)
        {
            if (students == null)                               
            {
                students.Add(student);                          
            }
            else
            {
                if ((students.Count(s => s.Id == student.Id)) == 1)   

                  // LINQ query, student id is unique
            {
                throw new ArgumentException("Error student " 
                  + student.Name + " is already in the class");
            }
            else
            {
                students.Add(student);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Bra*_*rad 5

另一种方法是使用a HashSet而不是a List.

Student类:

public class Student
{
    private int id;

    public override int GetHashCode()
    {
        return this.id;
    }
    public override bool Equals(object obj)
    {
        Student otherStudent = obj as Student;
        if (otherStudent !=null)
        {
            return this.id.Equals(otherStudent.id);
        }
        else
        {
            throw new ArgumentException();
        }

    }

    public int Id
    {
        get { return id; }
        set { id = value; }
    }

}
Run Code Online (Sandbox Code Playgroud)

然后你可以添加这样的东西

    HashSet<Student> hashSetOfStudents = new HashSet<Student>();
    Student s1 = new Student() { Id = 1 };
    Student s2 = new Student() { Id = 2 };
    Student s3 = new Student() { Id = 2 };

    hashSetOfStudents.Add(s1);
    hashSetOfStudents.Add(s2);
    hashSetOfStudents.Add(s3);
Run Code Online (Sandbox Code Playgroud)

添加s3将失败,因为它具有相同Ids2.