Sort by key incorrect for negative values

Hi @jacob.small

There appears to be a bug with the List.SortByKey (Dynamo 2.6.2) component not working when the number is a negative double…

1 Like

It’s nothing to do with negative values or doubles. It’s to do with a list of different data types being used as keys. They are first sorted by their data type, then by their value.

Try sortbykey with a list of [3, 2.5, 2, 1.5, 1]. You’ll see the doubles get moved to the front and then sorted into order, then the integers appear in their order.

You’ll either need to convert all values to doubles or all values to int to get your intended result.

1 Like

I agree with the logic but that’s definitely going to catch people out at times. Wonder if it would make more sense to force all ints to doubles before sorting if both key types are provided?

2 Likes

Probably not the worst idea. My introduction to programming was with languages where you declare a data type for every variable, but with Dynamo being the easy access platform I think it’s fair to make some assumptions. I can’t really see many scenarios where you’d want to sort those differently, and if you did you could workaround by sort/grouping by data type first. The standard list.sort node seems to infer both input types as a double based on the snips above, so they’re already partway there.

1 Like

If that’s true (which I suspect it is), why would List.Sort’s logic be different? It seems absurd that integers and numbers would be classified differently during a sorting process. @jacob.small can you clarify if this is intentional.

1 Like

I think this was fixed 2 years ago.

1 Like

Still works as per OPs snip on my end. 2.6.something

Clearly it hasn’t. Or at least not for version 2.6.2

yes, thats correct, I believe this was fixed in 2.10.

1 Like

Posting from my other account as I’m traveling some this morning…

This caught me off guard awhile back as well. Fortunately mixed data types are rare and generally should be avoided for sorting in any language (expanding the mixed type logic leads us to the question of which comes first in the list: [5, 5.0, “5”, “5.0”]?]. Also as noted by @Michael_Kirschner2 the behavior has been changed in 2.10, so fully updated Revit 2022 and up should work without issue.

If you need a fix for older builds/uses, you can convert the data type (Math.Round node to N digits) before sorting.