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);
}
}
}
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.
You can override Student.Equals() and Student.GetHashCode() to check if the Student.Id is equal. If the student list inherits from List<Student>, you can just use the default Add() method. It will only add students with different Ids.
public class Student
{
// ...
public override bool Equals(object obj)
{
// Check for null values and compare run-time types.
if (obj == null || GetType() != obj.GetType())
return false;
Student other = obj as Student;
return this.Id == other.Id;
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
}
public class StudentList : List<Student> { }
// Usage:
var students = new StudentList();
students.Add(student);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With