//define new List for Students
List<Student> listofStudents = new List<Student>();
private Student student;
//Save Button
private void saveButton_Click(object sender, EventArgs e)
{
student = new Student();
student.regNo = regNoTextBox.Text;
student.firstName = firstNameTextBox.Text;
student.lastName = lastNameTextBox.Text;
student.GetFullName();
listofStudents.Add(student);
regNoTextBox.Text = "";
firstNameTextBox.Text = "";
lastNameTextBox.Text = "";
}
这里我想如果regNo是唯一的,那么listofStudents将添加学生
答案 0 :(得分:1)
我认为您的要求是,如果列表中没有具有给定注册ID的学生,那么您是否要将此学生添加到列表中?
您可以使用Any
查找列表是否包含项目。
if (listofStudents.Any(item => item.regNo == student.regNo) == false)
{
listofStudents.Add(student);
}
答案 1 :(得分:0)
您可以使用一些计数器,每次添加到列表后将增加1:
private int Counter { get; set; }
然后你添加如下学生:
Student student = new Student()
{
regNo = Counter++,
firstName = "John",
lastName = "Doe"
};
listofStudents.Add(student);
答案 2 :(得分:0)
在@viveknuna解决方案的基础上,我建议如下:
为Student
类添加适当的构造函数:
public class Student
{
public string regNo { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public Student(string regno, string firstname, string lastname)
{
regNo = regno;
firstName = firstname;
lastName = lastname;
}
}
然后您的代码变为:
List<Student> listofStudents = new List<Student>();
private void saveButton_Click(object sender, EventArgs e)
{
if (!listofStudents.Any(item => item.regNo == regNoTextBox.Text))
{
listofStudents.Add(new Student(firstNameTextBox.Text, lastNameTextBox.Text, regNoTextBox.Text));
student.GetFullName();
}
regNoTextBox.Text = "";
firstNameTextBox.Text = "";
lastNameTextBox.Text = "";
}