Take the 2-minute tour ×

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.

share|improve this question
specifically ArrayList is an array of? –  naveen Aug 14 '11 at 7:41
Given that you're using C# 4, why are you using ArrayList instead of a generic collection? –  Jon Skeet Aug 14 '11 at 7:43
type student class. and this class has a constructor to set the values for name and subject. so you can say we have to give namea and subject as parameter while adding.like, list.Add(new student(john, maths)), where list is the name of the arraylist –  Sandy Aug 14 '11 at 7:44
You can simplify your code using LINQ, it will remove the 'i' declaration and the foreach loop, just use : var results = albums.FindAll(a => a.artist == txt || a.tag == txt); if you want only the first or last result just replace 'FindAll' with the 'First' or 'Last' method –  mmorel Aug 16 '11 at 7:16
thanks will try that. –  Sandy Aug 16 '11 at 18:20
add comment

2 Answers

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 :

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

share|improve this answer
Thanks mmorel, i shifted to list generics and it worked perfect. you can have a look at my edited code to see how i searched. welcome for suggestions. –  Sandy Aug 14 '11 at 19:26
add comment
up vote 0 down vote accepted

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;
share|improve this answer
add comment

Your Answer


