function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jonathan SpinkJonathan Spink 

How do I (dynamically) refer to a field in a loop given the fieldname as an input string?

So I'm looping through the records from a List and want to check the value of a field against the value from the previous record. But I want to be able to pass the name of the field to the method. Something like:

public static void (List<Contact> cList, string fieldname) {
integer i = 1;
for ( Contact c : cList) {
if (c[i].fieldname == c[i-1].fieldname) {
...
} else {
...
}

 
Best Answer chosen by Jonathan Spink
Jaya Karthik  karnatiJaya Karthik karnati
Hi Jonathan,

Yes we can pass the field name dynamically . Once you have passed the field name dynamically, capture the field name in a string and use get method to fetch the value.
 
list<contact> ConList=[Select id,name from contact];
system.debug('Size-->'+ConList.size());
integer i=0;
string FieldName='Name';
for(i=0 ; i<ConList.size() ; i++){
system.debug('Current contacts Name-->'+ConList[i].get(FieldName));
if(i!=0)
system.debug('previous contacts Name-->'+ConList[i-1].get(FieldName));
}

Hope this helps, If so kindly mark this as best answer.

Thanks,
Karthik

All Answers

Jaya Karthik  karnatiJaya Karthik karnati
Hi Jonathan,

I think so using a generic for loop would solve your requirement (to compare current records field name with previous records field name) .

I have tested the below mock code and it is working as expected. Hope it helps.
In my example i took the field name as account and i am able to fetch current record and previous record values in for loop.
 
list<contact> ConList=[Select id,name from contact];
system.debug('Size-->'+ConList.size());
integer i=0;
for(i=0 ; i<ConList.size() ; i++){
system.debug('Current contacts Name-->'+ConList[i].Name);
if(i!=0)
system.debug('previous contacts Name-->'+ConList[i-1].Name);
}


Thanks,
Karthik
Jonathan SpinkJonathan Spink
Thanks Karthik. But the problem is to do this for any field whose name ('fieldname' in my example) is passed into the method.
Jaya Karthik  karnatiJaya Karthik karnati
Hi Jonathan,

Yes we can pass the field name dynamically . Once you have passed the field name dynamically, capture the field name in a string and use get method to fetch the value.
 
list<contact> ConList=[Select id,name from contact];
system.debug('Size-->'+ConList.size());
integer i=0;
string FieldName='Name';
for(i=0 ; i<ConList.size() ; i++){
system.debug('Current contacts Name-->'+ConList[i].get(FieldName));
if(i!=0)
system.debug('previous contacts Name-->'+ConList[i-1].get(FieldName));
}

Hope this helps, If so kindly mark this as best answer.

Thanks,
Karthik
This was selected as the best answer
Jonathan SpinkJonathan Spink
That's it! Thanks Karthik.