搜索嵌套列表的最快方法<>在 C# 中
我有一个列表<>其中包含另一个 List<>
我需要查找给定值是否存在于最里面列表中的任何项目中。 如果找到匹配项,我需要该特定项目并返回。
我正在这样做,如下所示:
InnerList inner = null;
foreach(TopList in topListItems)
{
inner = asn.Owners.Find(x => x.GuestId == guestId);
if(inner != null)
break;
}
//item found if inner is not null
//else item absent in the inner list
Any other alternate way that may run faster than this?
编辑: 一些更正:我只需要查看内部列表是否有具有特定值的项目。 如果是,那么我需要返回具有匹配项的顶级项目。 我想逻辑是一样的。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这就是我使用 Linq 实现这一目标的方式。
或按照 Claytons 评论使用 Lambdas
但是,使用 GuestId 进行重构以使用键控字典会更快。
This would be how I would achieve this using Linq.
or using Lambdas as per Claytons comment
However refactoring to use a keyed dictionary using GuestId would be faster.
如果您想保留数据结构,那么我看到的唯一改进就是放弃基于委托的搜索和手动搜索。我预计这会带来约二倍的改善。
如果可能的话,您可以以某种方式使用字典。但我对你的问题了解不够,无法告诉你这是否可能。这可以带来非常大的加速,因为在字典中按键搜索是 O(1) 而不仅仅是 O(n)。
在某些情况下,
for
循环可能会比foreach
循环稍微加速,但我不知道这是否是其中之一。所以你需要进行基准测试。If you want to keep the data structure then the only improvement I see is throwing out the delegate based search and search manually. I expect an improvement of about factor two with that.
If possible you could employ dictionaries in some way. But I don't know enough about your problem to tell you if that's possible. This can give a really big speedup since a search by key in a dictionary is O(1) and not just O(n).
In some situations a
for
loop might give a slight speedup over theforeach
loop, but I don't know if this is one of them. So you'll need to benchmark.您可以递归地执行此操作。这段代码可能不适合你,但它会是这样的:
You can do it recursively. This code probably won't work for you, but it's gonna be something like it:
内部列表是否已排序?如果是这样,您可以对内部列表使用二分搜索,这将提供潜在的性能改进。此外,如果您可以控制内部列表的构造,则将其更改为以 GuestId 为键的字典将为您提供更优化的检查。
Is the inner list sorted? If so you could use a binary search for the inner list which would provide a potential performance improvement. Additionally if you have control over the construct of the inner list, changing it to a Dictionary keyed on GuestId would give you a more optimal check.
可能是这个吗?
Could be this?