0

I coded the following line of code

DATA(lt_heads_ok) = VALUE my_head_table( for wa IN g_heads
                      LET ok = g_model->is_head_ok( wa-id )
                      IN ( COND #(  WHEN ok = abap_true THEN wa ) ) ).

I can activate it but the results seems weird to me. Indeed I get all the lines but empties are none of them are valid according to my conditions.

Is there a way to avoid to append an empty line when it does not match the "COND" condition ?

Sandra Rossi
  • 11,934
  • 5
  • 22
  • 48
flowx1710
  • 177
  • 3
  • 16

1 Answers1

2

Adding lines conditionally in a FOR iteration can be done in two ways. Note that the same question arises even if LET is not used.

The first way is to use LINES OF:

CLASS lcl_app DEFINITION.
  PUBLIC SECTION.
    CLASS-METHODS is_ok IMPORTING sflight TYPE sflight RETURNING VALUE(result) TYPE abap_bool.
ENDCLASS.

CLASS lcl_app IMPLEMENTATION.
  METHOD is_ok.
    IF sflight-seatsmax - sflight-seatsocc > 10. result = abap_true. ENDIF.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  TYPES ty_sflights TYPE STANDARD TABLE OF sflight WITH DEFAULT KEY.

  SELECT * FROM sflight INTO TABLE @DATA(sflights).

  DATA(sflights_filtered) = VALUE ty_sflights( 
        FOR <sflight> IN sflights
        ( LINES OF COND #( 
              WHEN lcl_app=>is_ok( <sflight> ) = abap_true 
              THEN VALUE #( ( <sflight> ) ) ) ) ).

The second way is to use REDUCE:

  DATA(sflights_filtered) = REDUCE #( 
        INIT aux_sflights TYPE ty_sflights
        FOR <sflight> IN sflights
        NEXT aux_sflights = COND #( 
              WHEN lcl_app=>is_ok( <sflight> ) = abap_true 
              THEN VALUE #( BASE aux_sflights ( <sflight> ) )
              ELSE aux_sflights ) ).
Sandra Rossi
  • 11,934
  • 5
  • 22
  • 48
  • Thanks. Is there no other way by which we can avoid to create a new internal table for each row ? ( "THEN VALUE #( ( ) ) " ) – flowx1710 Oct 04 '18 at 12:56
  • Not that I know – Sandra Rossi Oct 04 '18 at 17:27
  • `Note, that the code above achieves the same result as` so why to complicate it overwhelmingly?)) SAP [uses LINES OF](https://help.sap.com/doc/abapdocu_752_index_htm/7.52/en-US/abenvalue_constructor_params_lspc.htm#!ABAP_ALTERNATIVE_2@2@) in a more simplistic way, and you construct table inline which is not good for performance – Suncatcher Jun 01 '19 at 10:29
  • @Suncatcher Agreed. I removed the paragraph "the code above achieves the same result" and I did an example such a way that there is no simpler solution. Moreover, I added a second solution based on `REDUCE`. – Sandra Rossi Jun 01 '19 at 16:01