2011-04-15 65 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