为什么会出现一个List< T> .BinarySearch(...)?

为什么会出现一个List< T> .BinarySearch(...)?

问题描述:

我在看表,我看到一个二分查找方法有几个重载,我不禁怀疑是否有意义都拥有这样的列表?

I'm looking at List and I see a BinarySearch method with a few overloads, and I can't help wondering if it makes sense at all to have a method like that in List?

为什么我会想要做一个二进制搜索,除非名单排序?如果没有排序的列表中,调用该方法也只是CPU时间的浪费。什么是有上列出方法呢?

Why would I want to do a binary search unless the list was sorted? And if the list wasn't sorted, calling the method would just be a waste of CPU time. What's the point of having that method on List?

排序和搜索上列出了两个非常常见的操作。这将是不友好通过不提供常规列表上的二进制搜索来限制开发商的选项

图书馆设计需要妥协 - 在.NET设计师选择了报价两个二进制搜索功能在C#中的数组的名单,因为他们可能觉得(像我一样),这些都是有用的,常见的操作,和谁选择调用它们之前,使用他们了解的先决条件(即列表被订购)的程序员。

Library design requires compromises - the .NET designers chose to offer the binary search function on both arrays an lists in C# because they likely felt (as I do) that these are useful and common operations, and programmers who choose to use them understand their prerequisites (namely that the list is ordered) before calling them.

这是很容易排序列表&LT; T&GT; 使用的 排序() 重载。如果你觉得你需要gaurantees排序一个不变的,可以随时使用 排序列表&LT; TKEY的,TValue&GT; 的SortedSet&LT; T&GT; 而不是

It's easy enough to sort a List<T> using one of the Sort() overloads. If you feel that you need an invariant that gaurantees sorting, you can always use SortedList<TKey,TValue> or SortedSet<T> instead.