2

在 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);
            }
        }
    }
4

8 回答 8

5

另一种方法是使用 aHashSet而不是 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; }
    }

}

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

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

添加s3将失败,因为它与Id相同s2

于 2012-10-30T18:59:07.690 回答
2

您可以覆盖Student.Equals()Student.GetHashCode()检查 Student.Id 是否相等。如果学生列表继承自List<Student>,您可以使用默认Add()方法。它只会添加具有不同 ID 的学生。

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);
于 2012-10-30T18:03:00.787 回答
1

不同项目的列表听起来非常像一

更新:为如何选择适当的数据结构编写一个好的动机有点乏味,我将向您展示一旦您更熟悉 .NET 框架,您将如何编写上述内容:

public void AddStudent(Student student)
{
    /* this.students is an ISet<Student> */
    if (!this.students.Add(student))
    {
       throw new ArgumentException("student");
    }
}

这当然假设Student具有Equals()GetHashCode()的合适定义。根据使用的具体 ISet 类型,您实际上可能会通过GetHashCode()的良好定义获得一些不错的副作用,但该讨论可能有点超出了这个问题的范围。

于 2012-10-30T18:03:25.820 回答
1

我会使用字典

students Dictionary<int, Student> = new Dictionary<int, Student>();

然后检查你是否已经有那个学生

if (!students.ContainsKey(student.id))
{
      students.add(student.id, student);
}
于 2012-10-30T18:06:19.537 回答
1

使用foreach循环:

    public void AddStudent(Student student)
    {
        if (students == null)
        {
            students.Add(student);
        }
        else
        {
            foreach (var s in students)
            {
                if (student.Id == s.Id)
                {
                    throw new ArgumentException("Error student "
                    + student.Name + " is already in the class");
                }
            }
            students.Add(student);
        }
    }
于 2012-10-30T18:08:26.713 回答
0

有很多方法可以做到这一点,这里有两种可能的解决方案

1. 您可以遍历您的列表。

bool alreadyInList = false;
foreach (var item in students) 
{
 if (item.Id == student.Id)
 {
    alreadyInList = true;
    break; // break the loop
 }
}

if (!alreadyInList)
{
   students.Add(student);
} 
else
{
     throw new ArgumentException("Error student " 
              + student.Name + " is already in the class");
}

2. 覆盖对象Equals中的方法Student并使用Contains.

public class Student 
{
    public override bool Equals(object x) 
    {
        return ((Student)x).Id == this.Id;
    }
}

if (!students.Contains(student)) 
{
   students.Add(student);
} 
else 
{
     throw new ArgumentException("Error student " 
              + student.Name + " is already in the class");
}

更多信息:

于 2012-10-30T18:04:55.063 回答
0

将保存学生的结构设为 a并通过ContainsKeydictionary<int,Student>检查 ID 是否已在字典中。

于 2012-10-30T18:05:13.723 回答
-1

首先将所有可用的 id 读入listor ,然后通过检查orarray确保新 id 与现有 id 不匹配。listarray

于 2012-10-30T18:11:05.487 回答