Click here to Skip to main content
15,899,005 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,

I am new to .net and i have a situation where need to write the foreach loop but i am not aware of it exactly but i wrote for loop. Can anyone help me converting the below code to foreach?

Below is my code:

C#
List<Int32> multiObject = ((List<Int32>)favoriteDocumentsField.Value);
     for (int index = 0; index < multiObject.Count; index++) {
          Int32 docID = multiObject[index];
          Console.WriteLine("Artifact: {0} Field: {1} Value: {2}", employee.ArtifactID, favoriteDocumentsField.Name + " Object " + index, docID);
     }

Any help would be appreciated.

What I have tried:

I tried searching in google. I got the direct FOREACH loop examples and used but didn't get the conversion from the for to foreach.
Posted
Updated 23-Aug-16 0:48am

1 solution

Untested

C#
List<Int32> multiObject = ((List<Int32>)favoriteDocumentsField.Value);
     foreach (int docID in multiObject) {
          Console.WriteLine("Artifact: {0} Field: {1} Value: {2}", employee.ArtifactID, favoriteDocumentsField.Name, docID);
     }


I've dropped writing the index value from your WriteLine as it no longer exists. If you really want that index value you're better leaving it as a for loop. You could have index as its own variable and increment it inside the foreach, but there is not point in doing that when you can keep it as a for loop instead.
 
Share this answer
 
Comments
Member 8010354 23-Aug-16 6:53am    
List<int32> multiObject = ((List<int32>)favoriteDocumentsField.Value);
foreach (int docID in multiObject) {
emailAddress += docID.Artifact.Fields[0].Value.ToString() + ";";
}
In the above code, i am getting an error near Artifact inside loop stating int does not contain a definition for Artifact.
F-ES Sitecore 23-Aug-16 7:07am    
That's because docID is an int, so you can't do

docID.Artifact

You need to know what exactly has the Atrifact property if you want to access it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900