简体   繁体   English

在列表中查找项目的最快方法?

[英]Fastest way to find an item in a list?

I have an unsorted list of strings.我有一个未排序的字符串列表。 I can place these items in an array, List, SortedList, whatever.我可以将这些项目放在一个数组中,List、SortedList 等等。

I need to find the fastest way of looking up a string in this list.我需要找到在此列表中查找字符串的最快方法。 Am I better off dumping the list into an array, sorting it, then implementing binary search?我最好将列表转储到数组中,对其进行排序,然后实现二分查找吗? Or does the framework provide a way to do this?或者框架是否提供了一种方法来做到这一点?

Thanks谢谢

PS Using VS2008 against .NET 2.0 PS 使用 VS2008 对抗 .NET 2.0

If your goal is just to make it very fast to find the strings in a collection, put them into a HashSet .如果您的目标只是快速查找集合中的字符串,请将它们放入HashSet 中

HashSet.Contains is an O(1) method, and strings have a good hash algorithm by default, so it will be difficult to make a faster routine than this. HashSet.Contains是一个 O(1) 方法,字符串默认有很好的哈希算法,所以很难做出比这更快的例程。


Edit:编辑:

Since you're using .NET 2, I would just do Dictionary<string,string> and use the same string for key and value.由于您使用的是 .NET 2,我只会执行Dictionary<string,string>并使用相同的字符串作为键和值。 Dictinoary<TKey,TValue>.Contains is also O(1), and will be much faster than any list-based searching you attempt. Dictinoary<TKey,TValue>.Contains也是 O(1),并且比您尝试的任何基于列表的搜索都要快得多。

If you will only have to find one object, one time, just start at the beginning and look at each one until you find it.如果您一次只需要找到一个对象,只需从头开始,逐个查看,直到找到为止。 If you will have to repeat this Find operation multiple times against the same list, to find different items, then sort it keep the sorted list and do a binary search...如果您必须针对同一个列表多次重复此 Find 操作,以找到不同的项目,然后对其进行排序,保留已排序的列表并进行二分搜索...

I'm not sure whether this will be of any use to you, but this would be a fairly simple way of doing it, not sure on the exact "speed" of it though.我不确定这对您是否有用,但这将是一种相当简单的方法,但不确定它的确切“速度”。

List<string> collection = new List<string>();

collection.Sort();

foreach(string value in collection)
{
   if(value == "stringToLookFor")
   {
       return value;
   }
{

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM