使用 LINQ 查询列表的最佳方法
我有一个集合
IEnumerable<Project>
,我想根据项目的 Id 属性进行过滤,以包含列表中的任何 id:
List<int> Ids
执行 where 子句来检查属性是否包含在列表中的最佳方法是什么。
i have a collection
IEnumerable<Project>
and i want to do a filter based on project's Id property to included any id that is in a list:
List<int> Ids
what is the best way to do a where clause to check if a property is contained in a list.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您也许能够使用
Except
方法获得更有效的实现:棘手的是
Except
适用于相同类型的两个集合 - 因此您想要两个项目集合。您可以通过创建新的“虚拟”项目并使用仅根据 ID 比较项目的comparer
来实现这一点。或者,您可以仅对 ID 集合使用
Except
,但随后您可能需要通过 ID 查找项目,这使得这种方法不太有吸引力。You may be able to get a more efficient implementation using the
Except
method:The tricky thing is that
Except
works with two collections of the same type - so you want to have two collections of projects. You can get that by creating new "dummy" projects and usingcomparer
that compares projects just based on the ID.Alternatively, you could use
Except
just on collections of IDs, but then you may need to lookup projects by the ID, which makes this approach less appealing.var nonExcludedProjects = from p in allprojects where Ids.Contains(p => p.Id) select p;
var nonExcludedProjects = from p in allprojects where Ids.Contains(p => p.Id) select p;
如果您要使用 .Where(p=> list.Contains(p)) 答案之一,您应该考虑首先从列表中创建一个 HashSet,这样它就不必执行 O(n )每次都搜索。这将运行时间从 O(mn) 减少到 O(m+n)。
If you're going to use one of the .Where(p=> list.Contains(p)) answers, you should consier first making a HashSet out of the list so that it doesn't have to do an O(n) search each time. This cuts running time from O(mn) to O(m+n).
我不确定我是否理解你的问题,但我会尝试一下。
如果你有: IEnumerable 可枚举,
并且您想要对其进行过滤,使其仅包含列表中也存在的项目:列表列表,
然后: IEnumerable Final = enumerable.Where(e => list.Contains(e));
I'm not sure that I understand your question but I'll have a shot.
If you have: IEnumerable enumerable,
and you want to filter it such that it only contians items that are also present in the list: List list,
then: IEnumerable final = enumerable.Where(e => list.Contains(e));