如何使用单个项目从列表中查找和显示多个项目?

时间:2016-11-20 05:48:13

标签: c#

    //declaring new list
    List<Student>studentslist=new List<Student>();
    public Student student;        
    //Save Button
    private void button1_Click(object sender, EventArgs e)
    {
        Student student = new Student();
        student.regNo = regNoTextBox.Text;
        student.firstName = firstNameTextBox.Text;
        student.lastName = LastNameTextBox.Text;
        student.GetFullName();

        if (studentslist.Any(item => item.regNo == student.regNo) == false)
        {
            studentslist.Add(student);
            regNoTextBox.Text = "";
            firstNameTextBox.Text = "";
            LastNameTextBox.Text = "";
            MessageBox.Show("Information Saved.");
        }
        else
        {
            MessageBox.Show("The Reg.No is alresy exist !");
        }

在这里,我为学生添加了独特的Reg.No。现在我要输入任何已保存的Reg.No,然后按Find Button,它将在MessageBox中显示相应的学生姓名。我怎么能这样做?

3 个答案:

答案 0 :(得分:0)

您可以使用

等唯一注册值搜索学生
Student s=studentlists.Where(item=>item.regNo==textbox_regNumber).FirstorDefault();
if(s!=null)
{
   MessageBox.Show(s.studentName + " Class: " +s.class +" Section: "+s.section);
}
else
{
   MessageBox.Show("Not Found")
}

答案 1 :(得分:0)

如果您想要dictionary的唯一学生:

,则可以创建regNo
    var studentsList =Dictionary<string, Student>` for adding students with unique regNo:

    private void button1_Click(object sender, EventArgs e)
    {
        var regNo = regNoTextBox.Text;
        if(!studentsList.ContainsKey(regNo))
        {
            Student student = new Student();
            student.regNo = regNoTextBox.Text;
            student.firstName = firstNameTextBox.Text;
            student.lastName = LastNameTextBox.Text;
            student.GetFullName();
            studentsList.Add(regNo, student);
            regNoTextBox.Text = "";
            firstNameTextBox.Text = "";
            LastNameTextBox.Text = "";
            MessageBox.Show("Information Saved.");
        }        
        else
        {
            MessageBox.Show("The Reg.No already exists !");
        }
    }

答案 2 :(得分:0)

List<Student>studentslist=new List<Student>();
public Student student;        
//Save Button
private void button1_Click(object sender, EventArgs e)
{
    Student student = new Student();
    student.regNo = regNoTextBox.Text;
    student.firstName = firstNameTextBox.Text;
    student.lastName = LastNameTextBox.Text;
    student.GetFullName();
    Student s=studentlists.Where(item=>item.regNo==textbox_regNumber).FirstorDefault();

    if(s!==null)
    {
        studentslist.Add(student);
        regNoTextBox.Text = "";
        firstNameTextBox.Text = "";
        LastNameTextBox.Text = "";
        MessageBox.Show("Information Saved.");
    }
    else
    {
        MessageBox.Show("The Reg.No is alresy exist !");
    }
}