使用 LINQ 查询列表的最佳方法

发布于 2024-10-18 21:40:58 字数 195 浏览 2 评论 0原文

我有一个集合

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

半葬歌 2024-10-25 21:40:58
var filteredProjectCollection = projectCollection.Where(p => Ids.Contains(p.id));
var filteredProjectCollection = projectCollection.Where(p => Ids.Contains(p.id));
无名指的心愿 2024-10-25 21:40:58

您也许能够使用 Except 方法获得更有效的实现:

var specialProjects = Ids.Select(id => new Project(id));
var filtered = projects.Except(specialProjects, comparer); 

棘手的是 Except 适用于相同类型的两个集合 - 因此您想要两个项目集合。您可以通过创建新的“虚拟”项目并使用仅根据 ID 比较项目的 comparer 来实现这一点。

或者,您可以仅对 ID 集合使用 Except,但随后您可能需要通过 ID 查找项目,这使得这种方法不太有吸引力。

You may be able to get a more efficient implementation using the Except method:

var specialProjects = Ids.Select(id => new Project(id));
var filtered = projects.Except(specialProjects, comparer); 

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 using comparer 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.

独闯女儿国 2024-10-25 21:40:58

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;

夜夜流光相皎洁 2024-10-25 21:40:58

如果您要使用 .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).

小帐篷 2024-10-25 21:40:58

我不确定我是否理解你的问题,但我会尝试一下。

如果你有: 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));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文