如何在数组列表中进行搜索

发布于 2024-11-29 14:52:46 字数 232 浏览 0 评论 0原文

我创建了一个 Student 类型的数组列表。 Student 中有姓名、科目信息。假设我的 ArrayList 具有 (sam, maths)、(john, english)、(mat, science) 等值。如果我想找出哪个学生有科学流,那么如何在 ArrayList 中搜索它。

我认为这可以通过使用binarysearch或indexof方法来完成,但没有得到正确的结果。

I created an arraylist of Student type. Student has name, subject information in it. Suppose my ArrayList has values like (sam, maths), (john, english), (mat, science). If i want to find out which student has science stream, then how to search it in an ArrayList.

I think it may be done by using binarysearch or indexof methods, but not getting it right.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风流物 2024-12-06 14:52:46

为什么要创建 Student 类型的数组列表?

我很确定您应该使用通用类型安全列表:List

要进行搜索,您可以使用 LINQ:

List<Student> students = new List<Student>();
students.Add(new Student { Lastname = "Smith" });
students.Add(new Student { Lastname = "Foo" });
students.Add(new Student { Lastname = "SmithFoo" });
students.Add(new Student { Lastname = "SmithBar" });

var searchResults = from student in students
     where student.Lastname.StartsWith("Smith")
     select student;

此代码将在您的学生列表中搜索并返回三个学生:史密斯、史密斯福和史密斯巴

Why did you created an arraylist of Student type ?

I'm pretty sure that you should go with a generic type-safe list : List<T>

To do your searches you could use LINQ :

List<Student> students = new List<Student>();
students.Add(new Student { Lastname = "Smith" });
students.Add(new Student { Lastname = "Foo" });
students.Add(new Student { Lastname = "SmithFoo" });
students.Add(new Student { Lastname = "SmithBar" });

var searchResults = from student in students
     where student.Lastname.StartsWith("Smith")
     select student;

This code will search in your students list and return three students : Smith, SmithFoo and SmithBar

等待圉鍢 2024-12-06 14:52:46

我最后就是这么做的。抱歉我忘记回答这个问题了。

  public int search(object sender, List<albums> al)
    {
        int i = -1;
        TextBox txt = (TextBox)sender;
        foreach (albums dc in al)
        {
            if ((dc.artist == txt) ||(dc.tag == txt))
            {
                i = (al.IndexOf(dc));
            }
        }
        return i;
    }

Thats how I did in the end. Sorry I forgot to answer this one.

  public int search(object sender, List<albums> al)
    {
        int i = -1;
        TextBox txt = (TextBox)sender;
        foreach (albums dc in al)
        {
            if ((dc.artist == txt) ||(dc.tag == txt))
            {
                i = (al.IndexOf(dc));
            }
        }
        return i;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文