开发者

Can I search a sorted List<T> faster when it is sorted on the fields I search on?

I thougt that sorting a List<T> on the fields I search on would make the s开发者_如何学Goearch faster. Suppose I have a List<Person> of 10.000 and a List<Car> of 10.000 in an object Model. I loop the Persons list in the Model and want to find the Car with the property c.Owner == person.Name.

public static Car Car(Model model, Person person)
        {
            return model.Cars.Find(
                 delegate(Car c)
                 {
                     return c.Owner.Equals(person.Name);
                 });
        }

Sorting the list of cars on property owner doesn't make the loop faster?

I thought maybe I should use BinarySearch but the overloads of BinarySearch do not permit delegates. What is überhaupt the use of BinarySearch when you have to give the Car you want to lookup as a parameter?


List<T>.BinarySearch doesn't accept a delegate, but it does have an overload that accepts an IComparer<T>. Use that overload with the appropriate custom comparer (CarByOwnerComparer : IComparer<Car>) to get it to search the way you want it to. Of course, bear in mind that the list has to be already sorted with that comparer to allow binary-search to work. If you prefer writing a delegate (e.g. through a lambda) to implementing an interface, consider using a converter that can translate between the two, such as the ProjectionComparer provided here.

However, I would suggest that you use a more appropriate collection-class instead, which provides fast retrieval by key. For example, SortedList<,> and SortedDictionary<,> will both do the job in O(logn). If ordering is not a true requirement, it might be a lot easier to just go with Dictionary<,>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜