4

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

2 Answers 2

5

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.

0
2

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

2
  • You could just do it with a formula, no?
    – Adrian Larson
    Jan 4, 2016 at 23:03
  • Splitting and unsplitting is so last year...
    – sfdcfox
    Jan 4, 2016 at 23:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .