Search code examples
genexus

Is there a way to know when a For each is on his first and last Iteration on genexus X v3?


I am using a for each to call a command that generates a report but I need the first and last report with somehow different data than the others, Is there a way to know this on genexus X v3 ?


Solution

  • If you only need to discriminate the first iteration from the remaining ones you may just use a boolean variable. This can also be used when, in the last iteration, you need to do something after what you do in every other iteration:

    &first = true
    for each
      if &first
        &first = false
        // Do whatever you need in the first iteration
      else
        // Do whatever you need in the remaining iterations
      endif
    endfor
    
    // Do whatever you need to do after the last iteration 
    

    If you need to do something different in the last iteration instead of what you do for every other iteration you need to delay your action one iteration and use buffer variables to hold the previous values.

    For example, suppose you need to use two attributes CustomerCode, CustomerName and you need to call Procedure1 for the first iteration, Procedure2 for the remaining less the last iteration and Procedure3 for the last one:

    &first = true
    &rest = false
    for each
      if &first
        &first = false
        // Do whatever you need in the first iteration
          Procedure1(CustomerCode, CustomerName)
      else
        if &rest
        // Do whatever you need in the remaining iterations, using buffer variables             
           Procedure2(&CustomerCode, &CustomerName)
        else
           &rest = true
        endif
        // Load buffer variables
        &CustomerCode = CustomerCode
        &CustomerName = CustomerName
      endif
    endfor
    
    // Do whatever you need in the last iteration, using buffer variables
    if &rest
     Procedure3(&CustomerCode, &CustomerName)
    endif