我有一个包含超过 75,000 个对象的列表。要从当前列表中搜索项目,我正在使用以下代码。
from nd in this.m_ListNodes
where
nd.Label == SearchValue.ToString()
select
nd;
这段代码是否高效?
最佳答案
您需要多久搜索一次同一个列表?如果您只搜索一次,您还不如进行直线搜索 - 虽然您可以通过调用 SearchValue.ToString()
一次 使当前代码稍微更高效在查询之前。
如果您要多次对同一个列表执行此搜索,您应该构建一个Lookup
或一个Dictionary
:
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
}
关于c#-4.0 - 从 C# 中的对象列表中搜索对象的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5673714/