什么是最有效的方式来发现的两个集合联盟? [英] What is the most efficient way to find union of two collections?

查看:118
本文介绍了什么是最有效的方式来发现的两个集合联盟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public IEnumerable<SummaryItem> GetSummaryData(SummarySettings settings)
{
   return GetSummaryReportData(startTime, endTime, settings.AgentIds);
}

在我写我的code,我意识到,我需要一些 IDS 添加到 settings.AgentIds

After I wrote my code I realized that I need to add some ids to the settings.AgentIds.

所以,我做了以下

public IEnumerable<SummaryItem> GetSummaryData(SummarySettings settings)
{
    if (settings.LabelIds != null && settings.LabelIds.Any())
    {
       var labelGroups = _agentsGroupsStorage.Values.Where(x => settings.LabelIds.Contains(x.Id));
       var labelAgentIds = labelGroups.SelectMany(x => x.AgentIds); // IEnumerable<Guid>

       settings.AgentIds = new GuidCollection(labelAgentIds.Union(settings.AgentIds).ToList());
    }

   return GetSummaryReportData(startTime, endTime, settings.AgentIds);
}

如何才能提高我的算法来合并两个集合?

How can I improve my algorithm to combine two collection?

也许,而无需创建新GuidCollection ?或者我需要使用总结而不是联盟

Maybe without creating new GuidCollection ? Or I need to use Aggregate but not Union?

推荐答案

下面是一个联盟的近似实现:

Here is the approximate implementation of a Union:

public IEnumerable<T> Union(this IEnumerable<T> left, IEnumerable<T> right)
{
    var hs=new Hashset<T>(left);
    for(var item in right)
    {
        hs.Add(item);
    }
    return hs;
}

正如你所看到的,它使用基于集合的集合,使工会。此利用哈希表的速度,使操作非常有效的确实。有可能以与前-knowlege您试图收集数据的一个更优化的解决方案,但在一般情况下,这是因为快速,因为它得到

As you can see, it makes use of a set-based collection to make the union. This leverages the speed of hash tables to make the operation very efficient indeed. It might be possible to make a more optimal solution with fore-knowlege of the data that you are trying to collect, but in the general case, this is as quick as it gets.

这篇关于什么是最有效的方式来发现的两个集合联盟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆