in sql I have a table like:
PersonOrganisationRole
which has the columns:
PersonId, OrganisationId RoleId
So it’s a three way table between Person, Organisation and Role.
So I was wanting to create a way to get all the Organisations a Person belongs to:
public class Person
{
public IEnumerable<Organisation> Organisations
{
get
{
var organisations = new List<Organisation>();
foreach (var personOrganisationRole in PersonOrganisationRoles.Where(personOrganisationRole => !organisations.Contains(personOrganisationRole.Organisation)))
{
organisations.Add(personOrganisationRoles.Organisation);
}
return organisations;
}
}
}
So I’m basically populating a list by iterating through all items in the table and only adding the org if I haven’t added it already. This is important because there could be multiple rows in the table with the same PersonId and OrganisationId due to the fact a person could have multiple roles at an organisation.
I’m thinking though there must be a far better way of writing this code.
Any suggestions?
A combination of the Linq Select() and Distinct() methods should do it.