2011-04-15 64 views
0

我有一个包含超过75万个对象的列表。要从列表中搜索项目,我正在使用以下代码。从c中的对象列表中搜索对象的有效方法#

from nd in this.m_ListNodes 
where 
    nd.Label == SearchValue.ToString() 
    select 
    nd; 

此代码是否有效?

+0

尝试有时候接受一些答案:) – Marco 2011-04-15 07:39:58

+1

@Marco:在OP已要求总5个问题(包括这个问题)的回答很少。它*可能*还没有得到足够好的答案。 – 2011-04-15 07:47:18

回答

9

你多长时间需要搜索同一个列表?如果您只搜索一次,您还可以直接进行线性搜索 - 尽管您可以通过在查询之前调用SearchValue.ToString()一次来使当前代码的效率略高。

如果你要在同一名单上多次执行此搜索,您应该建立一个LookupDictionary

var lookup = m_ListNodes.ToLookup(nd => nd.Label); 

var dictionary = m_ListNodes.ToDictionary(nd => nd.Label); 

使用字典,如果有每个标签只有一个条目;如果可能有多个匹配,请使用查找。

使用这些,对于查找:

var results = lookup[SearchValue.ToString()]; 
// results will now contain all the matching results 

或字典:

WhateverType result; 
if (dictionary.TryGetValue(SearchValue.ToString(), out result)) 
{ 
    // Result found, stored in the result variable 
} 
else 
{ 
    // No such item 
} 
+1

+1:比我的更干净,更短 – 2011-04-15 07:52:15

4

不。如果您使用Dictionary或HashSet作为标签作为关键字会更好。在你的情况下,字典是更好的选择:

var dictionary = new Dictionary<string, IList<Item>>(); 

// somehow fill dictionary 

IList<Item> result; 
if(!dictionary.TryGetValue(SearchValue.ToString(), out result) 
{ 
    // if you need an empty list 
    // instead of null, if the SearchValue isn't in the dictionary 
    result = new List<Item>(); 
} 

// result contains all items that have the key SearchValue 
+0

如果他正在尝试查找该项目,则'HashSet'不起作用。如果只有一个匹配项,字典将起作用,但如果多个项目具有相同的标签,则字典将失败。 – 2011-04-15 07:41:49

+0

我用字典尝试还是需要时间。代码是:from nd in.m_NodeDict 其中 nd.Key == SearchValue.ToString() select nd.Value; – Indrajeet 2011-04-15 07:42:38

+0

@JonSkeet:如果您使用错误,Dictionary只会失败。如果有多个具有相同标签的项目,请使用'Dictionary >'。问题解决了。 – 2011-04-15 07:47:00