Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何最有效地搜索对象列表?_C#_Performance_List_For Loop - Fatal编程技术网

C# 如何最有效地搜索对象列表?

C# 如何最有效地搜索对象列表?,c#,performance,list,for-loop,C#,Performance,List,For Loop,我有一个对象的列表,其中有几个字段。 如何最有效地搜索此列表以查找特定的对象? 现在,我只做了一个For循环,如下所示: for(int i = 0; i < theList.Count; i++) { if (theList[i].certainField == whatImLookingFor) { doSomething(); break;//to exit for loop to prevent unnecessary processing } } f

我有一个
对象的
列表
,其中有几个字段。 如何最有效地搜索此列表以查找特定的
对象
? 现在,我只做了一个For
循环,如下所示:

for(int i = 0; i < theList.Count; i++)
{
  if (theList[i].certainField == whatImLookingFor)
  {
    doSomething();
    break;//to exit for loop to prevent unnecessary processing
  }
}
for(int i=0;i

有没有更有效的方法?这通常是我正在比较的同一个字段。我想也许应该使用字典,但不确定是否应该使用。

这取决于你的用法

如果需要多次执行此操作,并希望尽可能快地执行,请创建字典:

//save a dictionary somewhere
var dictionary = theList.ToDictionary(i => i.certainField);

//execution:
var item = dictionary[whatImLookingFor];
dosomething();
这是以创建字典(更长的初始化时间)为代价的,但会提供更快的查找O(1)

如果只需要执行一次,则保持代码原样(O(n)查找)

顺便说一句,您并不知道.NET Dictionary[index]操作符是如何在内部实现的(例如,循环遍历数组或在底层使用指针链表)


我建议您阅读一篇关于.NET数据结构效率(数组、堆栈、字典、列表)的深入分析,尽管它在几年前就已经写好了,但它仍然有效,值得一看

这将在您找到的第一个对象时停止,这是您想要的吗?谢谢您的评论。是的,我总是在列表中寻找一个特定的对象。那么,我不认为通过建立一个字典可以改善这一点,除非你的对象列表非常庞大。如果你真的在寻找几个对象,我会选择一个
地图
,但是由于你在第一个对象上停下来,你将花费更多的时间来构建字典,而不是按照你目前的方式进行搜索;那么我就不需要for循环了,我只需要做字典[whatImLookingFor](whatImLookingFor应该一直在那里)这是真的,是的,但是你仍然需要注入到这本字典中(顺便问一下,那是什么语言?),所以这取决于你是否值得。
theList.First(x => x.certainField.Equals(whatImLookingFor)); //already optimized