Search code examples
c#adobeacrobat-sdk

C# : Replace while loop with ForEach (Acrobat SDK)


Can this be replaced with ForEach or IEnumrable

 IAFormApp formApp = new AFormAppClass();    
 IFields myFields = (IFields)formApp.Fields;
 IEnumerator myEnumerator = myFields.GetEnumerator();
 while (myEnumerator.MoveNext())
 { 
   IField myField = (IField)myEnumerator.Current;
 }

myEnumerator.MoveNext() is not iterating sequentially through my PDF Fields.


Solution

  • I am not familiar with the Adobe SDK API. But I think you are closer than you think. It seems that IFields is derived from IEnumerable or IEnumerable<IField>.

    In C#, you can use foreach to iterate through a collection.

    For example:

     IAFormApp formApp = new AFormAppClass();    
     IFields myFields = (IFields)formApp.Fields;
     
     foreach(IField field in myFields)
     {
       // do something with the field
     }
    

    In the background, foreach uses IEnumerable.GetEnumerator() or the generic IEnumerable<T>.GetEnumerator() to iterate over the elements in the collection. The mentioned method GetEnumerator() returns an IEnumerator respectively IEnumerator<T>.

    You need to check where IFields is derived from. If it is derived from IEnumerable<IField>, you can use the example above. If it derives from IEnumerable, you need to convert the object to the desired object type, because IEnumerator.Current returns an object.

    For more information on using IEnumerable or the generic form IEnumerable<T>, see the C# Programming Guide.