How to effectively combine the two collections?

I have the following algorithms to find the union of two collections.

IEnumerable<IGroup> labelGroups = _agents.Where(x => settings.LabelIds.Contains(x.Id));
IEnumerable<Guid>labelAgentIds = labelGroups.SelectMany(x => x.AgentIds);

settings.AgentIds = new Collection<Guid>(labelAgentIds.Union(settings.AgentIds).ToList());

or

IEnumerable<IGroup> labelGroups = _agents.Where(x => settings.LabelIds.Contains(x.Id));
agentIds = labelGroups.Aggregate(agentIds, (current, label) => current.Union(label.AgentIds));

Which should i use? Help me compare these algorithms (speed and memory).

+4
source share
1 answer

For best performance starting settings.LabelIdsatHashSet

var labelIds = new HashSet<int>(settings.LabelIds);

Then use the hashset to quickly find O (1)

var labelAgentIds = _agents.Where(x => labelIds.Contains(x.Id)).SelectMany(x => x.AgentIds);

If you know that labelAgentIdsand settings.AgentIdsnever have the same ID, you can use Concat, or use Unionto avoid duplicates.

settings.AgentIds = new Collection<Guid>(labelAgentIds.Union(settings.AgentIds).ToList())

Use Aggregatewill be slower.

+5
source

Source: https://habr.com/ru/post/1608976/


All Articles