如何在Realm中使用Linq表达式检查Nullable类型的null? [英] How to check for null on Nullable types using Linq expression in Realm?

查看:154
本文介绍了如何在Realm中使用Linq表达式检查Nullable类型的null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取所有未设置Modified属性但似乎无法使其与Realm一起使用的元素.

I want to get all elements where the Modified property isn't set but can't seem to get it to work with Realm.

示例代码:

public class FooModel : RealmObject
{
  public DateTimeOffset? Modified { get; set; }
}

...

public List<FooModel> GetAllUnmodified()
{
  var realm = Realm.GetInstance();

  //doesn't work
  var result1 = realm.All<FooModel>().Where(model => model.Modified == null).ToList();

  //doesn't work
  var result2 = realm.All<FooModel>().Where(model => !model.Modified.HasValue).ToList();

  //doesn't work
  DateTimeOffset? testValue = null;
  var result3 = realm.All<FooModel>().Where(model => model.Modified == testValue).ToList();

  //doesn't work
  var result4 = realm.All<FooModel>().Where(model => model.Modified == default(DateTimeOffset?)).ToList();

  return result1;
}

始终获取System.NotSupportedException: The rhs of the binary operator 'Equal' should be a constant or closure variable expression.System.NotSupportedException: The member 'HasValue' is not supported

我错过了什么吗?有没有很好的方法来查看Realm的Linq实际支持什么?

Did I miss anything? Is there a good way to see what actually is supported by Realm's Linq?

在Android上使用Realm Xamarin v0.77.1

Using Realm Xamarin v0.77.1 on Android

我确实尝试过根据评论者的建议创建linq表达式树.这导致了System.MissingMethodException: Method 'RealmResults'1.get_Provider' not found.异常.

I did try creating a linq expression tree as suggested by a commenter. This resulted in a System.MissingMethodException: Method 'RealmResults'1.get_Provider' not found. exception.

推荐答案

以后看到的人请注意-此功能已在0.77.0版本中添加,并在当前的0.78.1中有效.

Note for anyone seeing this later - this feature was added in version 0.77.0 and is live in the current 0.78.1.

我们现在支持与null的比较.

We now support comparison to null.

public class Person : RealmObject
{
    public bool? IsAmbivalent { get; set; }
...
_realm.All<Person>().Where(p => p.IsAmbivalent == null);

或者,对于字符串属性,还要检查:

Or, for string properties, also checking:

_realm.All<Person>().Where(p => string.IsNullOrEmpty(p.OptionalAddress));

请参见单元测试以获取更多示例

这篇关于如何在Realm中使用Linq表达式检查Nullable类型的null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆