Mr.Potkin Mr.Potkin - 3 months ago 30
C# Question

Join two collection

I have a collection

persons
that contains
id
and
name
:

Dictionary<int, string> persons;



1 John

2 Pitter

3 Carl


Then I have a collection with person ids by organization:

IDictionary<int, IEnumerable<int>> workers;



100 - [1,2]

101 - []

102 - [3]


And finally I have the main entity that contains only OrganizationId:

entity.OrganizationId = 100;


I need to go through
workers
and get all ids of persons (it will give:
1,2
), to finally get the names of those persons from
persons
. How can I do that?

Answer

If you just want the persons from this particular OrganisationId:

var personsFromOrganisation = workers[OrganizationId].Select(i => persons[i]);

If you want an object that directly associates all OrganisationId to corresponding persons (here using a dictionary):

var organisationsIds = entities.Select(e => e.OrganisationId).Distinct();
var personsByOrganisation = organisationsIds.ToDictionary(id => id, id => workers[id].Select(pid => persons[pid]));