【问题标题】:How to loop through a list of objects and search for a string in C#如何遍历对象列表并在 C# 中搜索字符串
【发布时间】:2016-04-14 20:37:27
【问题描述】:

我创建了一个应用程序,您可以在其中将学生和讲师添加到每个列表中,我需要搜索列表以按姓名或 ID 查找学生或讲师。但是,当我在列表中循环查找匹配的字符串时,它会找到匹配的字符串并打印详细信息,但是对于列表中的每个其他成员来说,表示未找到学生的 else 语句都会被触发。我尝试在 if 语句之后放置一个 break,但它仍然会发生。我该如何解决这个问题?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBSManagement
{
    class College: Staff
    {
        public static List<Student> students = new List<Student>();
        public static List<Lecturer> lecturers = new List<Lecturer>();

        static void Main()
        { 
            int choice;
            bool seeAgain = true;

                do
                {
                    Console.WriteLine("Press");
                    Console.WriteLine("1: To add a student");
                    Console.WriteLine("2: To add a lecturer");
                    Console.WriteLine("3: To search for a lecturer or student");
                    Console.WriteLine("4: To show the details of all enrolled students");
                    Console.WriteLine("5: To show the names of all lecturers");
                    Console.WriteLine("6: To show payroll details for a lecturer");
                    Console.WriteLine("7: To quit");
                    int.TryParse(Console.ReadLine(), out choice);

                    switch (choice)
                    {
                        case 1:
                            AddStudent();
                            break;
                        case 2:
                            AddLecturer();
                            break;
                        case 3:
                            SearchPerson();
                            break;
                        case 4:
                            ShowStudents();
                            break;
                        case 5:
                            ShowLecturers();
                            break;
                        case 6:
                            ShowPayrollDetails();
                            break;
                        case 7:
                            seeAgain = false;
                            break;
                        default:
                            Console.WriteLine("Invalid option selected");
                            break;
                    }
                } while (seeAgain);
            }
        public static void AddStudent()
        {
            Student student = new Student();
            Console.WriteLine("Enter student name:");
            student.Name = Console.ReadLine();
            Console.WriteLine("Enter student address:");
            student.Address = Console.ReadLine();
            Console.WriteLine("Enter student phone number:");
            student.Phone = Console.ReadLine();
            Console.WriteLine("Enter student email:");
            student.Email = Console.ReadLine();
            Console.WriteLine("Enter student PPSN:");
            student.PPSN = Console.ReadLine();
            Console.WriteLine("Enter student status (postgrad or undergrad):");
            EnterStat:
                string stat = Console.ReadLine().ToLower();
                if (stat == "postgrad" || stat == "undergrad")
                {
                    student.Status = (Status)Enum.Parse(typeof(Status), stat);
                }
                else
                {
                    Console.WriteLine("Please enter either postgrad or undergrad:");
                goto EnterStat;
                }
            Console.WriteLine("Enter student ID:");
            int inStudentID;
            int.TryParse(Console.ReadLine(), out inStudentID);
            student.StudentID = inStudentID;
            students.Add(student);
        }

        public static void AddLecturer()
        {
            Lecturer lecturer = new Lecturer();
            Console.WriteLine("Enter lecturer name:");
            lecturer.Name = Console.ReadLine();
            Console.WriteLine("Enter lecturer address:");
            lecturer.Address = Console.ReadLine();
            Console.WriteLine("Enter lecturer phone number:");
            lecturer.Phone = Console.ReadLine();
            Console.WriteLine("Enter lecturer email:");
            lecturer.Email = Console.ReadLine();
            Console.WriteLine("Enter lecturer PPSN:");
            lecturer.PPSN = Console.ReadLine();
            Console.WriteLine("Enter lecturer ID:");
            lecturer.ID = Console.ReadLine();
            Console.WriteLine("Enter salary:");
            lecturer.Salary = decimal.Parse(Console.ReadLine());
            Console.WriteLine("Enter subject taught:");
            lecturer.SubjectTaught = Console.ReadLine().ToLower();
            lecturers.Add(lecturer);
        }

        public static void SearchPerson()
        {
            int searchChoice = 0;
            int studentSearch = 0;
            int lecturerSearch = 0;
            Console.WriteLine("Press:");
            Console.WriteLine("1 to search for a student");
            Console.WriteLine("2 to search for a lecturer");
            int.TryParse(Console.ReadLine(), out searchChoice);

            switch (searchChoice)
            {
                //search students
                case 1:
                    Console.WriteLine("Press:");
                    Console.WriteLine("1 to search by name");
                    Console.WriteLine("2 to search by student number");
                    int.TryParse(Console.ReadLine(), out studentSearch);

                    switch (studentSearch)
                    {
                        case 1:
                            Console.WriteLine("Enter student name:");
                            string studentNameSearch = Console.ReadLine();

                            foreach (Student student in students)
                                //(int i = 0; i < students.Count; i++)
                            {
                                if (student.Name.Contains(studentNameSearch))
                                {
                                    Console.WriteLine(student.ToString());
                                    break;
                                }
                                else 
                                {
                                    Console.WriteLine("Student name not found");
                                }
                            }
                            break;

                        case 2:
                            int studentIDSearch;
                            Console.WriteLine("Enter student number:");
                            int.TryParse(Console.ReadLine(), out studentIDSearch);

                            for (int i = 0; i < students.Count; i++)
                            {
                                if (students[i].StudentID == studentIDSearch)
                                {
                                    Console.WriteLine(students[i].ToString());
                                }
                                else
                                {
                                    Console.WriteLine("Student number not found");
                                }
                            }
                            break;

                        default:
                            Console.WriteLine("Invalid option selected");
                            break;
                    }
                    break;
                //search lecturers
                case 2:
                    Console.WriteLine("Press:");
                    Console.WriteLine("1 to search by name");
                    Console.WriteLine("2 to search by course taught");
                    int.TryParse(Console.ReadLine(), out lecturerSearch);

                    switch (lecturerSearch)
                    {
                        case 1:
                            Console.WriteLine("Enter lecturer name:");
                            string lecturerNameSearch = Console.ReadLine();
                            for (int i = 0; i < lecturers.Count; i++)
                            {
                                if (lecturers[i].Name == lecturerNameSearch)
                                {
                                    Console.WriteLine(lecturers[i].ToString());
                                }
                                else
                                {
                                    Console.WriteLine("Lecturer name not found");
                                }
                            }
                            break;

                        case 2:
                            Console.WriteLine("Enter course taught:");
                            string lecturerSubjectSearch = Console.ReadLine().ToLower();
                            for (int i = 0; i < lecturers.Count; i++)
                            {
                                if (lecturers[i].SubjectTaught == lecturerSubjectSearch)
                                {
                                    Console.WriteLine(lecturers[i].ToString());
                                }
                                else
                                {
                                    Console.WriteLine("Subject not found");
                                }
                            }
                            break;
                        default:
                            Console.WriteLine("Invalid option selected");
                            break;
                    }
                    break;

                default:
                    Console.WriteLine("Invalid option selected");
                    break;
            }
        }

        public static void ShowStudents()
        {
            //sort list by name
            List<Student> SortedStudents = students.OrderBy(o => o.Name).ToList();

            foreach (Student student in SortedStudents)
            {
                Console.WriteLine(student);
            }
        }

        public static void ShowLecturers()
        {
            //sort list by name
            List<Lecturer> SortedLecturers = lecturers.OrderBy(o => o.Name).ToList();

            foreach (Lecturer lecturer in SortedLecturers)
            {
                Console.WriteLine(lecturer.Name);
            }
        }

        public static void ShowPayrollDetails()
        {
            Console.WriteLine("Enter lecturer name:");
            string lecturerNameSearch = Console.ReadLine();
            for (int i = 0; i < lecturers.Count; i++)
            {
                if (lecturers[i].Name == lecturerNameSearch)
                {
                    Console.WriteLine(lecturers[i].PayrollDetails());
                }
                else
                {
                    Console.WriteLine("Lecturer name not found");
                }
            }
        }
    }
}

【问题讨论】:

  • 好吧,为自己节省大量不必要的代码行并使用 LINQ。
  • 静态列表 matchingStudents = students.Where(s => s.Name = searchVal).toList();
  • 我不知道 Linq 是什么,我在上大学,他们没有提到它。我会调查的!

标签: c# list oop for-loop foreach


【解决方案1】:

试试这个

            Boolean found = false;
            foreach (Student student in students)
            //(int i = 0; i < students.Count; i++)
            {
                if (student.Name.Contains(studentNameSearch))
                {
                    Console.WriteLine(student.ToString());
                    found = true;
                    break;
                }
            }
            if(found == false)
            {
                    Console.WriteLine("Student name not found");
            }​

【讨论】:

  • 我试过了,但它声称 found 已定义但从未使用过。
  • 警告没有任何意义。您是否正确复制代码?
  • 我认为这没有道理。很确定我复制正确。我又试了一次,第二个 if 语句的右括号给了我一个意外的字符错误。更没有意义。
  • 我删除了符号并重新输入了它,它不再抛出错误了。您的解决方案有效!不知道 Visual 为何大惊小怪。
【解决方案2】:

您的代码为列表中的每个元素 student 输出“未找到学生姓名”

  • 不满足条件student.Name.Contains(studentNameSearch)
  • 在列表中满足条件的第一个元素之前(如果存在这样的元素,否则为列表中的每个元素打印消息)。

只有在搜索整个列表之后, 才能确定没有学生满足条件。

一个可能的解决方案:

Student studentMatch = null;
foreach (Student student in students)
{
    if (student.Name.Contains(studentNameSearch))
    {
         studentMatch = student;
         break;
    }
}      
if (studentMatch == null)
{
     Console.WriteLine("Student name not found");
}
else
{
    Console.WriteLine(studentMatch.ToString());
}

【讨论】:

    猜你喜欢
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2018-07-06
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多