You need to sign in to do that
Don't have an account?

Apex List - storing multiple types
Hello,
I'm learning Apex and one thing I've come across is storing multiple sobject types in a List. For example:
List<Contact> myList = [SELECT ID, AccountID, FirstName, LastName, Account.Name FROM Contact];
In the above ID, AccountID, FirstName, and LastName are all fields from Contact so if I system.debug myList I will see these 4 fields. I won't however see the Account.Name field. Makes sense since the Account Name is from the Account object.
Couple of questions:
1. Since myList is of type Contact I was assuming that it wouldn't be able to store any fields that aren't from Contact. How is it that Account.Name is able to be stored in a Contact List?
2. How do I extract the Account Name from each of the records stored in myList? When I perform a SOQL query in Query Editor I see the Account Names there. But I'm at a loss as to how to extract the Names via Apex.
Thanks,
Mike
I'm learning Apex and one thing I've come across is storing multiple sobject types in a List. For example:
List<Contact> myList = [SELECT ID, AccountID, FirstName, LastName, Account.Name FROM Contact];
In the above ID, AccountID, FirstName, and LastName are all fields from Contact so if I system.debug myList I will see these 4 fields. I won't however see the Account.Name field. Makes sense since the Account Name is from the Account object.
Couple of questions:
1. Since myList is of type Contact I was assuming that it wouldn't be able to store any fields that aren't from Contact. How is it that Account.Name is able to be stored in a Contact List?
2. How do I extract the Account Name from each of the records stored in myList? When I perform a SOQL query in Query Editor I see the Account Names there. But I'm at a loss as to how to extract the Names via Apex.
Thanks,
Mike
All Answers
You are already extracting Acount name by Account,Name in SOQL. SFDC doesnt store account name in contact object. When we use Account.Name it pulls up account name along with contact and you can refer to that by mylist[0].Account.Name or record variable in for loop
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships.htm
Where I'm still confused concerns the List myList. I declared it as type Contact however it seems to be storing Account.Name. Since Account.Name is from the Account object how is this happening? Shouldn't myList only be able to store fields from the Contact object? Or is it able to somehow store fields from related objects as well?
Mike