0

我正在使用以下方法使用动态soql对联系人记录进行相当简单的查询:

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;    
}

我正在使用一个包装器类,contactLinesForPage 是我的包装器对象的列表:

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

当用户进行多次搜索时,我不想将记录重新添加到 searchResults 列表中。如何检查我的对象中是否已存在记录,这样我就不会在搜索中返回重复记录?

谢谢你的帮助。

4

2 回答 2

2

或者你可以使用地图。将 ContactWrapper 对象添加到地图。地图的关键是一个 id。如果他们添加重复的联系人,它只会覆盖已经存在的联系人。你的代码就是

aMap.put(cw.id, cw);  // one line eliminates duplicates.

当您想要 ContactWrappers 列表时,只需返回aMap.values();

如果您想抽象维护联系人集合的行为,请创建一个 ContactCollection 类并在其中隐藏实现。这将为类似情况提供更可重用的东西以及良好的模式。

于 2013-11-06T04:30:51.733 回答
1

只需添加检查 contactLinesForPage 是否已包含此联系人。像这样的东西:

  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, ''));
        }
    }
于 2013-10-28T14:55:32.063 回答