LINQ 组项目。单个项目可能属于多个组
我有一个 IEnumerable 项目,我想按相关类别对其进行分组。这些项目按与其关联的类别(即列表)进行分组,因此单个项目可能是多个类别的一部分。
var categories = numbers.SelectMany(x => x.Categories).Distinct();
var query =
from cat in categories
select new {Key = cat,
Values = numbers.Where(n => n.Categories.Contains(cat))};
我使用上面的代码,它确实有效,但我想知道是否有更有效的方法来执行此操作,因为当数字包含数千个值时,此操作可能会执行缓慢。
我几乎要求重构代码以提高效率。
I have an IEnumerable of items that I would like to group by associated categories. The items are grouped by the categories that are associated with them - which is a List - so a single item can potentially be a part of multiple categories.
var categories = numbers.SelectMany(x => x.Categories).Distinct();
var query =
from cat in categories
select new {Key = cat,
Values = numbers.Where(n => n.Categories.Contains(cat))};
I use the above code, and it does in fact work, but I was wondering if there was a more efficient way of doing this because this operation will likely perform slowly when numbers contains thousands of values.
I am pretty much asking for a refactoring of the code to be more efficient.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 LINQ 的内置分组功能,这应该比包含查找更快。然而,与任何与性能相关的问题一样,在决定如何重写您知道有效的代码之前,您应该真正编写代码来收集性能指标。您将使用的卷可能根本不存在性能问题。
所以,这是代码。这尚未经过测试,但类似的东西应该可以工作:
每个组都包含一个键和属于该键的一系列值:
You can use LINQ's built-in grouping capabilities, which should be faster than a contains lookup. However, as with any performance-related question, you should really write code to collect performance metrics before deciding how to rewrite code that you know works. It may turn out that there's no performance problem at all for the volumes you will be working with.
So, here's the code. This isn't tested, but something like it should work:
Each group contains a key and a sequence of values that belong to that key: