C# Collection/List - Unique ID

c#, list

Solution

Another approach would be to use a `HashSet` instead of a `List`.

The `Student` class:

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; }
    }

}

Then you can add stuff like this

    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);

The addition of `s3` will fail because it has the same `Id` as `s2`.

Problem

In C# I'm trying to create a list of objects and when a new thing is added to the list, it is checked to make sure the same ID isn't used. I have the solution in Linq but I'm trying to do it without 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); } } } ```

Original source

Related problems