Forum Discussion

WesleyS's avatar
WesleyS
New Member
8 months ago
Solved

Table.Sort, unexplainable behaviour with a two-argument function

I've created a simple table where I want to sort based on a calculation of month (as number) plus the number in the Value-column. When I sort using a one-argument function (the step #"Only a"), usin...
  • Hans-Georg_Puls's avatar
    8 months ago

    Hi WesleyS ,

    Power Query has certain expectations concerning the comparer function. If you don't meet these requirements Power Query doesn't necessarily react with an error message but with a unpredictable behaviour. Randomly switching is not unusual.

    The requirements for the comparer function are:

    • Two parameter (a,b). You miss this requirement in your first attempt
    • The sort function should compare two rows (a and b). You don't do that in attempt 1 and 2
    • The sort function must return certain values: (attempt 3 does that by accident)
      • a negative number => a comes before b
      • a zero => rows are equal
      • a positive number => a comes after b

    In your case it shouldn't even be necessary to use a comparer function, the following should work:

    Table.Sort(#"Added Custom", {{"Sort function", Order.Ascending}})

     

    If you absolutely need to use a comparer function, the solution should be like this one:
    Table.Sort(#"Added Custom", (a, b) => Value.Compare(a[Sort function], b[Sort function]))

     

    Hope that helps!