2

I am assuming that was asked already but I haven't seen it yet.

I have two lists listGoalsPrevYears and listGoalsCurrYear

How to check if any values in listGoalsCurrYear is in listGoalsPrevYears?

public List<Community_Plan_Goal_Setting__c> listGoalsCurrYear {get;set;}
public List<Community_Plan_Goal_Setting__c> listGoalsPrevYears {get;set;}
3
  • Can you edit your question to include the formal apex definitions of these objects? Something such as public List<sObject> someList { get; set; } would be greatly helpful to this question getting a quality answer. Oct 5, 2016 at 14:23
  • I added the definitions
    – Apex N-u-b
    Oct 5, 2016 at 14:29
  • 2
    What criteria are you using to determine if two objects are the same (same ID?, same values in a few fields?) The reason I ask is because a set is probably what you want to use (not a list), but sets don't work well for just a straight comparison of two sObjects
    – Derek F
    Oct 5, 2016 at 15:00

1 Answer 1

2

As far as I know, there is no special way to do this (like Any in LINQ). Assuming you are interested in whether a particular record is in both lists, you can write a method like:

public boolean containsAny(List<sObject> toSearch, List<sObject> values)
{
    for (sObject i : values)
    {
        for (sObject j : toSearch)
        {
            if ((ID)j.get('id') == (ID)i.get('id'))
            {
                return true;
            }
         }
     }
     return false;
}

If you are interested in whether any value in any field on one list is present on the same field in the other list, you could modify the above like:

public boolean containsAnyField(List<sObject> toSearch, List<sObject> values)
{
    if (toSearch.size() == 0)
    {
        return false;
    }
    Set<String> fieldList = toSearch[0].getSObjectType().getDescribe().fields.getMap().keySet();
    for (sObject i : values)
    {
        for (sObject j : toSearch)
        {
            for (string k : fieldList)
            {
                if (String.valueOf(i.get(k)) == String.valueOf(j.get(k)))
                {
                    return true;
                }
            }
         }
     }
     return false;
}

(I used String.valueOf because I think it should return whether or not a value of any type is equivalent to the same value of the same type regardless of the starting type, this has false positives and negatives though, like NaN)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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