为什么有一个List< T> .BinarySearch(...)? [英] Why is there a List<T>.BinarySearch(...)?

查看:155
本文介绍了为什么有一个List< T> .BinarySearch(...)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看List,我看到一个BinarySearch方法与一些重载,我不禁想知道是否有意义,有一个像List中的方法。

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时间。在List上使用该方法有什么意义?

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.

使用 Sort() 超载。如果您认为您需要一个不变式来进行排序,则可以随时使用 SortedList< TKey,TValue> SortedSet< T>

这篇关于为什么有一个List&lt; T&gt; .BinarySearch(...)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆