我有一个清单:
List<Student> allStudents = new List<Student>();
Run Code Online (Sandbox Code Playgroud)
包含超过94,000个Student对象,其中Student定义为:
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
}
Run Code Online (Sandbox Code Playgroud)
并按姓氏排序.
从其他源获取Student对象后,我想二元搜索List allStudents以仅基于Surname属性查找匹配项.例如,如果List allStudents中的现有记录是:
Student(8139241, "Flintstone", "Fred", "12/1/1967")
Run Code Online (Sandbox Code Playgroud)
我搜索该项目:
Student(7294311, "Flintstone", "Wilma", "14/6/1969")
Run Code Online (Sandbox Code Playgroud)
二进制搜索应该是成功的.
List.BinarySearch(T,IComparer)重载似乎是可能的,但它是一个可行的解决方案吗?还是有更好的策略?我将处理大量的记录和搜索,因此O(n)搜索功能将不可行.
提前致谢!
更新:我决定用Wintellect PowerCollections库中的MultiDictionary替换我的List.此MultiDictionary可以接受重复的键.
age*_*t-j 10
List.BinarySearch是一个很好的解决方案,可以像你期望的那样工作.这是一个链接,显示类似于 IComparer所需的解决方案.但是,他们的示例不使用Generic IComparer.
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);
}
...
}
Run Code Online (Sandbox Code Playgroud)