Here’s a short follow-up to my last post on conditional logic in M. After that post went live, Ehren Vox of the Power Query team made a good suggestion on Twitter: rather than hard-code the list of conditions and values inside the query, why not take those values from the Excel spreadsheet too? That way end-users can maintain the conditions and values themselves.
Here’s my Excel spreadsheet, now with two tables: one called Input, containing my input value, and one called CaseValues containing my conditions and return values.
And here’s my new query, a variation on the simple case statement query from my previous post, but this time using the values from the CaseValues table to drive the logic:
let
//load input value table from worksheet
Source = Excel.CurrentWorkbook(){[Name="Input"]}[Content],
//get input value from that table
InputValue = Source{0}[Input],
//load case values from worksheet as a table
CaseTable = Excel.CurrentWorkbook(){[Name="CaseValues"]}[Content],
//turn that table into a list and append the else condition to the end
CaseValues = List.Combine({Table.ToRows(CaseTable),{{InputValue, "Else condition"}}}),
//look for the input value in the CaseValues list and return the value associated with it
SimpleCase = List.First(List.Select(CaseValues, each _{0}=InputValue)){1}
in
SimpleCase
The output here, once again, is the text value “Five”. Two interesting things to notice here:
- I used the Table.ToRows() function to turn the table containing my case values into a list of lists
- I used List.Combine() to append the else condition (a list containing two values, the input value and the text “Else condition”) onto the end of the list returned by Table.ToRows()
I’ve added this example to my original demo workbook, which can be downloaded here.