Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have two fields in a table Date_Time__c & Activity__r.ExternalAID__c. I am trying to create a list of unique value pairs of these fields in apex. How can i go about doing this. I am not able to retrieve DISTINCT values from SOQL.

Date_Time__c      Activity__r.ExternalAID__c 
5/30/2015 18:00       2 
5/30/2015 21:00       1
5/31/2015 21:00       1 
5/31/2015 18:00       2
5/31/2015 18:00       2   -----> should not be added to the list
share|improve this question

Since you're using relationships, you'll probably want to create a wrapper class. It'd look like this:

public class Wrapper {
    DateTime dateValue;
    Integer guid;

    public Wrapper(DateTime dtValue, Integer uid) {
        dateValue = dtValue;
        guid = uid;
    }
    public Integer hashCode() {
        // This code might need some adjustment
        return String.valueOf(dateValue.format('yyyy-MM-dd HH:mm:ss', '0')+guid).hashCode();
    }
    public Boolean equals(Object o) {
        Wrapper other = (Wrapper)o;
        return dateValue == other.dateValue && guid == other.guid;
    }
}

Then, you can just add the records to a set:

Set<Wrapper> distinctValues = new Set<Wrapper>();
for(MyObj__c record: [SELECT Date_Time__c, Activity__r.ExternalAID__c FROM MyObj__c]) {
    distinctValues.add(new Wrapper(record.Date_Time__c, record.Activity__r.ExternalAID__c));
}

Later, you can convert the results to a list (via new List<Wrapper>(distinctValues)), or iterate over them directly.

(Edit): Updated the hashCode method. I had a feeling I was off a bit.

share|improve this answer
    
Learnt a new thing. Thanks! – javanoob Jan 5 at 0:49

One approach is to join the two values as a string "key", put them into a Set, then perform whatever operation you may need (or resplit them). Since a Set will by definition contain unique values, duplicates will be omitted from the final collection:

Set<String> concatenatedFields = new Set<String>();
List<SObject> records = [SELECT Date_Time__c, Activity__r.ExternalAID__c FROM SObject];
for (SObject so : records) {
   joinedFields.add(string.valueOfGmt(so.Date_Time__c) + so.Activity__r.ExternalAID__c);
}

** be careful with timezone conversion when casting DateTime to String

share|improve this answer
    
You could just do it with a formula, no? – Adrian Larson Jan 4 at 23:03
    
Splitting and unsplitting is so last year... – sfdcfox Jan 4 at 23:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.