Get object record with unique field from list

apexcustom-objectlistmapsoql

I want to remove People__c record from list based on field value I have list of custom object People__c with field Responsible__c which is another object id. I am getting list of id and want to get something like below code.

List<Id> ids = new List<Id>('1','2','3');
List<People__c> peoples  =  Select id,name  from People__c Where Responsible__c: = ids[0] ORDER BY Name LIMIT 1
List<People__c> peoples1 =  Select id,name  from People__c Where Responsible__c: = ids[1] ORDER BY Name LIMIT 1
List<People__c> peoples2 =  Select id,name from People__c Where Responsible__c =: ids[2] ORDER BY Name LIMIT 1

So maybe I must do something like that? But I don't know how. So if in List there are elements 'Test1,Test2,Test3,Test4' it must return one record with Test1, one with Test2 and so on. Even if reocrds with Test1 more than 1.

List<People__c> peoples  =  Select id,name  from People__c Where Responsible__c in :ids ORDER BY Name 
Map<Id,People__c> peopleMap = new Map<Id,People__c>();
for(People__c p : peoples) {
Map.put();
//add only one people for each element in list where responsible__c = each element from list.
}

Best Answer

you are moving in the correct direction, you should use Map, where the key is a unique id from list ids. This could be rephrased, as "I want to group selected records by specific field values, size of this group should be 1 record".

List<People__c> peoples  =  [
    SELECT Id, Name
    FROM People__c
    WHERE Responsible__c IN :ids
    ORDER BY Name
];

Map<Id, People__c> peopleMap = new Map<Id, People__c>();
for(People__c p : peoples) {
    if(!peopleMap.containsKey(p.Responsible__c)){
        peopleMap.put(p.Responsible__c, p);
    }
}

as a result, you will have Map peopleMap, where key is a Responsible__c Id and value is a People__c record

Related Topic