+ Start a Discussion
Abilash Kosigi 8Abilash Kosigi 8 

Retrieving Field values from a Map

querystring = select <all fields> of Car__C

List<Car__c> L = Database.query(querystring);
    Map<Id, Car__c> m = new Map<Id, Car__c>(L);

for (Car__c field : m.values())
    <Car_NO> (Here it should display car no of each car.
     Similaryly, any field value of each record needs to be diplayed.

Please help with this.
When you call m.values() the map ceases to be an issue. In your for loop you would do: 

for (Car__c aCar : m.values())
    System.debug(aCar.field_name__c); // output the value of this field in this car record to the log

I don't understand the reason why you are adding the List which is being queried and putting to map and then using map.Values() which would return same  List of records .

Can't we use the same List which is being queried ??
James LoghryJames Loghry
Vinit is correct, using your code example, there's little or no need for a list.  In fact, you could just do something similar to:

for(Car__c car : [Select fields of Car__c]){
    System.debug('Car name: ' + carName);

This would give you a similar result to map.values() in Peter's example, but since maps are unordered, Peter's list is unordered, where as the example above, using a list, is ordered.

In the map case, in addition to Peter's example, you could iterate over keySet(), and then use .get(key) to get your Car value.  An example of this is below:

Map<Id,Car__c> carMap = new Map<Id,Car__c>([Select Id,Name From Car__c]);

for (Id carId : carMap.keySet()){
    Car__c currentCar = carMap.get(carId);
    System.debug('Car name: ' +  currentCar.Name);