从c#中的对象列表中搜索对象的有效方法

时间:2011-04-15 07:36:58

标签: c#-4.0

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

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

这段代码是否有效?

2 个答案:

答案 0 :(得分:11)

您需要多久搜索一次相同的列表?如果您只搜索一次,那么您也可以进行直线搜索 - 尽管您可以通过在查询之前调用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 :(得分: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