I have a List:
List allStudents = new List();
that contains over 94,000 Student objects, where Student is define
List.BinarySearch is a good solution and works like you would expect. Here's a link that shows a solution similar to what you'll need for the IComparer. Their example doesn't use the Generic IComparer, though.
public class CompareCustomDataType : IComparer<Student> {
public int Compare(Student x, Student y)
{
if (x == y) return 0;
if (x == null) return -1;
if (y == null) return 1;
return String.Compare(x.Surname, y.Surname);
}
...
}
Define the IComparable<T>
interface for your Student
class. Then all the sort and comparison methods of your list, including BinarySearch()
will you use this one automatically.
It has the following limitation
I would suggest you to use Linq to find the Matching Data from your list.
var data = students.where(o => o.SurName='xxxxx');
> You can also use the Find or FindAll methods from the List object using predicates.
With that many entries you would probably be better off using a Dictionary<string, Student>
lookup, which would be amortized O(1). Although there could probably be multiple Students with the same surname, so it would have be something like Dictionary<string, List<Student>>
Also as Amit pointed out, using a binary search when there are duplicate items can be tricky, because you don't know which index you will get in the series of duplicates. You would have to search to the left and right of the returned index to see if any other matching surnames exist.