Forum Discussion
Table.Sort, unexplainable behaviour with a two-argument function
- 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!
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!
Yeah the actual function wasn't important, I just needed something to test with.
Glad to hear that PQ's odd behaviour with the (a, b) version is not unusual, since I haven't told PQ how to relate the rows.
Thank you!