[SalesForce] Loop through collection

I'm new to Salesforce and this loop is bugging me:

public String matchingDataGridIDs {get;set;}

    public void GetData(string defaultUserID)
    {
        //retrieve data for selected user
        List<myData> matchingDataGrid = [Select Id, Name, CreatedById, CreatedDate where Id = :defaultUserID];

        for (List<myData> i :matchingDataGrid.Count)
        {   
            matchingDataGridIDs =+ matchingDataGrid.Id + ',';
        }
}

I get the following error:

Error: Compile Error: Initial term of field expression must be a
concrete SObject: List

Best Answer

The way that your code reads here

List matchingDataGrid = [Select Id, Name, CreatedById, CreatedDate where Id = :defaultUserID];

    for (List<myData> i :matchingDataGrid.Count)

You are assuming that matchingDataGrid is a list of lists, which it is not. You want to loop over each object within the list, so the format for doing that would be

for(myData i : matchingDataGrid)

The full code would look something like this.

public String matchingDataGridIDs {get;set;}

    public void GetData(string defaultUserID)
    {
        //retrieve data for selected user
        List<myData> matchingDataGrid = [Select Id, Name, CreatedById, CreatedDate where Id = :defaultUserID];

        for (myData i :matchingDataGrid)
        {   
            matchingDataGridIDs += i.Id + ',';
        }
}
Related Topic