How to search in a Arraylist
I created an arr开发者_开发百科aylist 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.
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
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;
}
精彩评论