简体   繁体   中英

How do I order children in a database by value in strings and numbers in Firebase Realtime Database Unity

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.

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"

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM