skip to Main Content

I am trying to order a list of data snapshots in unity when the values are numbers and strings.
When I use dbReference.OrderByChild("score")
even if the values are in both numbers and strings which can be convertible to numbers, it is in order from the strings first and then the numbers.

I want the string to be converted to numbers and then order it that way.
I use strings to store numbers because (as to my knowledge) you can’t use BigIntegers in Firebase without using strings because the BigInteger would be too large to fit in the regular firebase number.

I want it ordered from largest to smallest as in a leaderboard. I tried to order it correctly after I fetched from the database but I was stuck and couldn’t found out how to do this.

I appreciate any help,
Thanks.

2

Answers


  1. Chosen as BEST ANSWER

    I just have figured it out. The method I used was to fetch from the database in any order and then store it in a dictionary. While storing in the dictionary I converted the numbers to a string and parsed that to a BigInteger and added it to the dictionary by using the .Add() function. Next, I sorted the dictionary by the value by doing: var sorted = from entry in users orderby entry.Value.score ascending select entry; Finally I looped through the reversed version and it worked! Even if the values stored in the database were numbers in a string!

    Hope this helps someone who came across my same issue. Thanks to everyone who tried to help!


  2. Firebase won’t do that type of data conversion for you.

    If you want to order on numbers, you should only store numbers.

    If you want/need to store numbers as string values, you’ll need to store them in a format where the lexicographical ordering matches the numerical order. The common way to do this is to prefix the string values with zeroes (or spaces) until they are all the same length.

    So for:

    1
    23
    456
    

    If the maximum value you can have is 999, you’d store these as:

    "001"
    "023"
    "456"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search