.net 中的快速并集和相交
假设我有几个对象列表,需要将它们合并/相交。目前我只是做这样的事情:
List result = lists[0];
for( int i = 1; i < lists.Count; i++ )
result = (op == 'and') ? result.Union(lists[i]).ToList()
: result.Intersect(lists[i]).ToList();
我相信这工作得非常慢,即使列表是按其字段之一排序的。我怎样才能让它更快?哈希集、树等?最好由.NET 4提供。
这些对象实际上是缓存的DataRows,因为依赖DB来进行这些操作似乎要慢得多。
Let's say I've got several lists of objects and need to union/intersect them. Currently I simply do something like this:
List result = lists[0];
for( int i = 1; i < lists.Count; i++ )
result = (op == 'and') ? result.Union(lists[i]).ToList()
: result.Intersect(lists[i]).ToList();
I believe this is working very slow, even though lists are sorted by one of their fields. How would I make it faster? Hashsets, trees, etc.? Preferable provided by .NET 4.
These objects are actually cached DataRows, as relying on DB to make these operations seems to be much slower.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,使用
HashSet
似乎是有意义的,是的 - 假设您真的不关心顺序,那么将所有内容来回转换为列表是没有意义的:拥有请注意,这里有“如果”。您可能想要:
Well using a
HashSet<T>
would seem to make sense, yes - there's no point converting everything to a list back and forth, assuming you really don't care about the order:It's somewhat ugly having the "if" there, mind. You might want: