.net 中的快速并集和相交

发布于 2024-12-27 12:23:38 字数 350 浏览 0 评论 0原文

假设我有几个对象列表,需要将它们合并/相交。目前我只是做这样的事情:

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

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

发布评论

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

评论(1

浅笑轻吟梦一曲 2025-01-03 12:23:38

好吧,使用 HashSet 似乎是有意义的,是的 - 假设您真的不关心顺序,那么将所有内容来回转换为列表是没有意义的:

var result = new HashSet<Foo>(lists[0]);
foreach (var list in lists.Skip(1))
{
    if (op == "and")
    {
        result.UnionWith(list);
    }
    else
    {
        result.IntersectWith(list);
    }
}

拥有请注意,这里有“如果”。您可能想要:

var result = new HashSet<Foo>(lists[0]);
Action<IEnumerable<Foo>> action = op == "and"
     ? result.UnionWith : result.IntersectWith;
foreach (var list in lists.Skip(1))
{
    action(list);
}

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:

var result = new HashSet<Foo>(lists[0]);
foreach (var list in lists.Skip(1))
{
    if (op == "and")
    {
        result.UnionWith(list);
    }
    else
    {
        result.IntersectWith(list);
    }
}

It's somewhat ugly having the "if" there, mind. You might want:

var result = new HashSet<Foo>(lists[0]);
Action<IEnumerable<Foo>> action = op == "and"
     ? result.UnionWith : result.IntersectWith;
foreach (var list in lists.Skip(1))
{
    action(list);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文