Search code examples
listpowerquerym

Powerquery add multiple custom columns


I have a table (myTable) with following column names :

COUNTRY
CLPC
C_Prod1
C_Prod2
...
C_Prod15
E_Prod1
E_Prod2
...
E_Prod15

I have a list ProdList = {Prod1, Prod2, ..., Prod15} and would like to make use of that list to add 15 new EC_Prodx columns (as many as in my ProdList) which should contain : the value of CLPC if C_Prodx = 2 and E_Prodx = 2, otherwise "n/a"

e.g :

Table.AddColumn(myTable, "EC_Prod1", each if [E_Prod1] = 2 and [C_Prod1] = 2 then [CLPC] else "n/a")

Due to the number of Prodx, and the fact this ProdList may change, I would like to find a generic way to refer to EC_Prodx, C_Prodx, E_Prodx column names.

How can I loop through all values in my ProdList to add my EC_Prodx columns ? With regards

I have tried :

 AddColumns = List.Accumulate(ListeProd, myTable,(state, current) => Table.AddColumn(state, "EC_" & current, each if [E_ & current] = 2 and [C_ & current] = 2 then [CLPC] else "n/a"))

but [E_ is highlighted as invalid identifier


Solution

  • How about

    let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    new_list={"Prod1","Prod2","Prod3"},
    cycle =
      List.Accumulate(new_list,Source,(current_table, new_name) =>
      Table.AddColumn(current_table, "EC_"&new_name, each 
      if Record.Field(_,"C_"&new_name)=Record.Field(_,"E_"&new_name) then [CLPC] else "NA")
    )
    in cycle
    

    enter image description here