Setting userprofile properties backed by term sets that have the same names

When setting a userprofile property backed by a term set in CSOM we use this snippet (sample from Office Dev PNP)

// Get the people manager instance for tenant context
PeopleManager peopleManager = new PeopleManager(clientContext);

// Update the City property for the user using account name.
peopleManager.SetSingleValueProfileProperty(UserAccountName, "City", "Paris"); 

This works great. But if we have nested terms with the same name like for example:

image

Then we have a problem. We can only give a name with this method. We cannot use the corresponding guid or a path like USA: Paris. When we execute this code SharePoint will use one of these terms at random. You cannot specify which term it should take.

Solution

The solve this we can add an extra label to the term and use this value.

image

Now we can do

// Get the people manager instance for tenant context
PeopleManager peopleManager = new PeopleManager(clientContext);

// Update the City property for the user using account name.
peopleManager.SetSingleValueProfileProperty(UserAccountName, "City", "USA_Paris");