Supported Linq query expressions in Realm

Sooner or later, you’ll come to the point, that you don’t only want to get objects by Id or the whole set of objects of a specific type in Realm. The easiest, but probably most unsophisticated way to do it, would be just use a function on a Linq-Where statement. That’s easy and has reasonable performance, no need to iterate and implement it yourself. But it actually is a big waste of resources, because depending upon the function, every single element needs to be evaluated.

But there is a better way to do so, eventhough it’s support in Realm is very confined. You can use Linq-Expressions. In the next table you find a plan, on what is supported or not:

ExpressionExampleRealmInfo
Int-Query
Double-Query
String-Query
class.Number==4
class.Number>3.4
class.Number<=2
class.Text==”Hello World”
String-Functions:
Contains, StartsWith, EndsWith
class.Text.StartsWith(“T”)as StringComparison you can use Ordinal or OrdinalIgnoreCase
advanced calculationclass.Number*20>100no left-side operations are supported, but right-side operations
Same-Object Comparisonclass.Number>class.Number2only comparison with constant values are supported
List-Functionsclass.List.Contains(3)
Sub-Object-Accessclass.SubClass.Number==1
Take()Take(20)
Skip()Skip(5)

That’s really not a lot. Actually it ends up with numeric type comparisons (==,<,>..) and some string-Comparer (==,Contains, StartsWith, EndsWith). I really hope Mongo Inc. will spend some more time on implementing more Linq-Expression features in Realm.

But actually there is a (little) work around (which I didn’t yet check out in terms of performance). You can use the Filter-function, which takes a query that is inspired by NSPredicate. (you can find more details here)

ExpressionFilter
advanced calculation
Same-Object ComparisonSubClass.Number>Number
List-FunctionsANY SubClassArray.Number>10
ANY or SOME works only with RealmObject-Arrays, not with atomic type arrays
Sub-Object-AccessSubClass.Number>20
Take()
Skip()

Summarizing my investigation and research on this, I can say: There’s space for improvement. I am very keen on finding out, whether MongoRealm will have a more sufficient way to query data.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.