Search code examples
salesforceapex-code

Do not add object to object list if already exists


I am doing a fairly simple query for contact records using dynamic soql using the following method:

public PageReference contactSearch() {
    contactResultSetSize = 0;
    if(!String.isEmpty(firstname) || !String.isEmpty(lastname) || !String.isEmpty(company)) {
        string soql = 'Select firstname, lastname, account.Name, account.BillingStreet, account.BillingCity, account.BillingState, account.BillingPostalCode From Contact';
        String whereClause = ''; 

        if(!String.isEmpty(firstname)) {
            whereClause = ' Where firstname like \'%' + firstname + '%\'';
        }
        if(!String.isEmpty(lastname)) {
            if(!String.isEmpty(firstname)) {
                whereClause += ' AND lastname like \'%' + lastname + '%\'';
            }
            else {
                whereClause = ' Where lastname like \'%' + lastname + '%\'';
            }
        }
        if(!String.isEmpty(company)) {
            if(!String.isEmpty(firstname) || !String.isEmpty(lastname)) {
                whereClause += ' AND account.Name like \'%' + company + '%\'';
            }
            else {
                whereClause = ' Where account.Name like \'%' + company + '%\'';
            }
        }
        soql = soql + whereClause;

        List<Contact> searchResults = Database.query(soql);
        contactResultSetSize = searchResults.size();
        if(contactLinesForPage == null) {
            contactLinesForPage = new List<ContactWrapper>();
        }

        for(Contact c : searchResults) {
            contactLinesForPage.add(new ContactWrapper(contactLinesForPage.size(), c, ''));
        }
    }
    return null;    
}

I am using a wrapper class and contactLinesForPage is a list of my wrapper object:

public List<ContactWrapper> contactLinesForPage {get; set;}

As a user does multiple searches, I don't want to re-add records to the searchResults list. How can I check if a record already exists in my object so I don't have duplicate records returned in the search?

Thanks for any help.


Solution

  • Just add a check if contactLinesForPage allready contains this contact. Something like this:

      for(Contact c : searchResults) {
            Boolean toInsert = true;
            for(ContactWrapper cw : contactLinesForPage){
                 if(cw.contact.Id == c.Id){
                     toInsert=false;
                 }
            }
            if(toInsert){
               contactLinesForPage.add(new ContactWrapper(contactLinesForPage.size(), c, ''));
            }
        }