Dom*_*que 2 c# indexing performance list
我IList<Node>
在 C# 中有 a , aNode
是一个对象,具有Name
属性。
通常,我需要在该内部执行搜索IList<Node>
,我的操作如下:
List_of_Nodes.Where(o => o.Name == "Something").FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
我想知道是否有办法加快速度。
在数据库中,通过在要搜索的列上创建索引,可以更快地执行表内的搜索。
这在 C# 中也可能吗IList
?
(我一直在该网站上查找,但我总是得到类似的结果List_of_Nodes[index]
。如果我可以将搜索替换为List_of_Nodes[name]
,那就太好了,但我怎样才能实现这一点呢?
根据您可以使用的每个键是否存在重复项Dictionary<TKey,TValue>
(或带有自定义比较器的哈希集):
表示键和值的集合。
var indexByName = nodeList.ToDictionary(n => n.Name);
// or
var indexByName = nodeList
.GroupBy(n => n.Name)
.ToDictionary(g => g.Key, g => g.First()); // or g => g.ToArray()
Run Code Online (Sandbox Code Playgroud)
并通过索引器(如果不存在将抛出)或通过方法按键访问值TryGetValue
。
表示一组键,每个键映射到一个或多个值。A
Lookup<TKey,TElement>
类似于Dictionary<TKey,TValue>
. 区别在于 aDictionary<TKey,TValue>
将键映射到单个值,而 aLookup<TKey,TElement>
将键映射到值的集合。
var indexByName = nodeList.ToLookup(node => node.Name);
Run Code Online (Sandbox Code Playgroud)
并使用索引器通过 来访问数据key
,如果key
在集合中没有找到,则返回一个空序列。
笔记:
To...
方法都允许指定比较器,例如支持不区分大小写的比较 -nodeList.ToLookup(n => n.Name, StringComparer.OrdinalIgnoreCase)