How to use Union with different type of collections?

My method will need to return a collection that contains settings.AgentIds and agent ids that correspond to settings.LabelIds. So I decided to use Union

IEnumerable<IAgentsGroup> labelGroups = _agentsGroups.Values.Where(x => settings.LabelIds.Contains(x.Id));

IEnumerable<IEnumerable<Guid>> labelAgentIds = labelGroups.Select(x => x.AgentIds);

return labelAgentIds.Union(settings.AgentIds);

But I dont now how to combine it into the one Collection<Guid>,

beacuse settings.AgentIds has type Collection<Guid> and labelAgentIds has IEnumerable<IEnumerable<Guid>> type?

Jon Skeet
people
quotationmark

If you're content to just flatten the IEnumerable<IEnumerable<Guid>> into an IEnumerable<Guid> in the obvious way, then SelectMany is your friend:

IEnumerable<Guid> labelAgentIds = labelGroups.SelectMany(x => x.AgentIds);
return labelAgentIds.Union(settings.AgentIds);

Whereas Select maps each single element in the input to another single element in the output, SelectMany maps each single element in the input to any number of elements in the output (maybe 0, maybe 1, maybe more).

people

See more on this question at Stackoverflow