Anatoly
Anatoly

Reputation: 1916

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?

Upvotes: 1

Views: 184

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460068

I think you want to flatten the IEnumerable<Collection<Guid>>, then use SerlectMany:

var allGuids = labelAgentIds.SelectMany(col => col).Union(settings.AgentIds);
Collection<Guid> result = new Collection<Guid>(allGuids.ToList());

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500165

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).

Upvotes: 3

Haney
Haney

Reputation: 34792

You can use SelectMany to flatten the collection:

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

Upvotes: 1

Related Questions