Binary Search a List of custom data types to match just one field

前端 未结 4 1636
清酒与你
清酒与你 2021-01-21 15:07

I have a List:

List allStudents = new List(); 

that contains over 94,000 Student objects, where Student is define

相关标签:
4条回答
  • 2021-01-21 15:13

    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);
      }
    ...
    }
    
    0 讨论(0)
  • 2021-01-21 15:27

    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.

    0 讨论(0)
  • 2021-01-21 15:31

    It has the following limitation

    1. If the List contains more than one element with the same value, the method returns only one of the occurrences, and it might return any one of the occurrences, not necessarily the first one.
    2. The List must already be sorted according to the comparer implementation; otherwise, the result is incorrect.

    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.

    0 讨论(0)
  • 2021-01-21 15:33

    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.

    0 讨论(0)
提交回复
热议问题