You can use a Map
. A typical example would look something like:
Set<Id> contactIds = new Set<Id>();
for (User lUser : lUsers) contactIds.add(lUser.ContactId);
contactIds.remove(null);
Map<Id, Account> contactIdToAccount = new Map<Id, Account>();
for (Account account : [SELECT PersonContactId FROM Account])
if (!contactIdToAccount.containsKey(account.PersonContactId))
contactIdToAccount.put(account.PersonContactId, account);
for (User lUser : lUsers)
{
Account firstPersonAccount = contactIdToAccount.get(lUser.ContactId);
// do stuff
}
However, note that there can be multiple matches.* It probably makes more sense to update all of them, and also use a separate Map
to de-duplicate.
Set<Id> contactIds = new Set<Id>();
for (User lUser : lUsers) contactIds.add(lUser.ContactId);
contactIds.remove(null);
Map<Id, List<Account>> contactIdToAccounts = new Map<Id, List<Account>>();
for (Account account : [SELECT PersonContactId FROM Account])
{
if (!contactIdToAccount.containsKey(account.PersonContactId))
contactIdToAccount.put(account.PersonContactId, new List<Account>());
contactIdToAccount.get(account.PersonContactId).add(account);
}
Map<Id, Account> uniqueAccounts = new Map<Id, Account>();
for (User lUser : lUsers)
{
List<Account> personAccounts = contactIdToAccount.get(lUser.ContactId);
if (!personAccounts == null)
{
for (Account personAccount : personAccounts)
{
// do stuff
uniqueAccounts.put(personAccount.Id, personAccount);
}
}
}
* The relationship is set up as many to one. I am not certain if you can actually associate multiple Person Accounts
to the same Contact
.