我在C#中有一个IList<Node>,Node是一个对象,有Name作为属性.

我需要定期在这IList<Node>内执行搜索,具体操作如下:

List_of_Nodes.Where(o => o.Name == "Something").FirstOrDefault();

I would like to know if there is a way to speed that up.
In a database, a search within a table can be executed faster by creating an index on the column you want to search on.

Is that also possible in a C# IList?
(I've been looking on the site, but I always get results like List_of_Nodes[index]. It would be great it I could replace the search by List_of_Nodes[name], but how can I achieve that?

推荐答案

您可以try 使用Dictionary作为索引(类似于数据库中的散列索引);让它成为Dictionary<string, Node[]>:对于给定的Key 我们得到一个对应的Node数组:

// Build Dictionary based index
var myIndex = List_of_Nodes
  .GroupBy(node => node.Name)
  .ToDictionary(group => group.Key, group => group.ToArray());

...

// Ask index if it has nodes with "Something" Name...
var result = myIndex.TryGetValue("Something", out var nodes)
  ? nodes[0] // ... if it has, obtain the 1st one
  : null;

Csharp相关问答推荐

在Linq中调用需要limit和offset的方法''''

有没有一种方法可以防止在编译时在MicrosoftC或非单线程上下文中调用方法?

如何从HttpContext获取请求正文

.NET 8 Web-API返回空列表

不带身份的Blazor服务器.Net 8 Cookie身份验证

将轮询与超时同步

如何捕获对ASP.NET核心应用程序的所有请求并将其发送到一个页面

从VS调试器而不是测试资源管理器运行的调试NUnitDotNet测试

.NET 8 DI GetServices<;对象&>不工作

避免只读记录 struct 中的防御副本

在ASP.NET Core 8 MVC中本地化共享视图

.NET8->;并发词典总是比普通词典快...怎么回事?[包含基准结果和代码]

如何在发布NuGet包之前设置命名空间?

JSON串行化程序问题.SQLite中的空值

如何从非异步任务中正确返回TypeResult

在同一个捕获中可以有多种类型的异常吗?

毛伊岛.NET 8图片不再适合按钮

多个参数的最小API删除

使用C#12中的主构造函数进行空判断

C#LINQ多行条件