1

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?

Anatoly
  • 1,908
  • 4
  • 25
  • 47
  • possible duplicate of [Flatten IEnumerable>; understanding generics](http://stackoverflow.com/questions/9440497/flatten-ienumerableienumerable-understanding-generics) – Razvan Dumitru Sep 23 '15 at 11:54

3 Answers3

3

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

You can use SelectMany to flatten the collection:

IEnumerable<Guid> labelAgentIds = labelGroups.SelectMany(x => x.AgentIds);
Haney
  • 32,775
  • 8
  • 59
  • 68
1

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());
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939