Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

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

I have a List:

List<Student> allStudents = new List<Student>(); 

that contains over 94,000 Student objects, where Student is defined as:

public class Student
{
    public Int32 ID { get; set; }
    public String Surname { get; set; }
    public String Other_Names { get; set; }
    public String DOB { get; set; }
    // remaining fields omitted
}

and sorted by Surname.

After grabbing a Student object from another source, I want to binary search the List allStudents to find a match based ONLY on the Surname property. For example, if an existing record in the List allStudents is:

Student(8139241, "Flintstone", "Fred", "12/1/1967")

and I search for the item:

Student(7294311, "Flintstone", "Wilma", "14/6/1969")

the binary search should be a success.

The List.BinarySearch(T, IComparer) overload appears to be a possibility, but is it a viable solution? Or is there a better strategy? I will be dealing a lot of records and searches, so O(n) search functions will not be viable.

Thanks in advance!

UPDATE: I've decided to replace my List with a MultiDictionary from the Wintellect PowerCollections library. This MultiDictionary can accept duplicate keys.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
  }
...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...