我正在使用 Realm + Xamarin Forms 来执行我认为可能是最基本的操作: ListView 显示项目集合,搜索栏在用户键入时过滤结果。
我有一个只获取集合属性用作 ListView 的项目源,最初从 Realm 查询填充,并且随着数据的任何更改自动更新,但我无法弄清楚如何在没有的情况下更新搜索文本添加一个集合并从字面上替换整个集合。
这是非常低效的——我认为这会触发为集合及其中的每个项目重新注册一堆通知更改的事件监听器,并且通常会在点击每个字母时造成大量困惑。
在过去,我创建了自己的包装可观察集合,并使用搜索方法来处理这个问题,我想这也是一个选项,但是有什么方法可以用 Realm 做到这一点吗?也就是说,要在不重新创建整个集合的情况下更新查询,是否可以通过某种方式重新运行原始查询?
最佳答案
更新:此技术不再有效。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~
...it also differs from the behavior of LINQ to Objects, where every iteration will reevaluate expressions, meaning that changes to both sides of a condition will affect the result. A Realm query will evaluate the right-hand sides of the conditions on the first run.
当您构建包含基于非 Realm 条件的Where
参数的查询时,查询结果不会在这些变量/参数更改时更新,除非您再次更新/执行查询。
Realm queries are live, in the sense that they will continue to represent the current state of the database.
所以我做的是创建一个过滤器类(RealmObject
),然后如果你实例化一个“过滤器对象”,将它保存到 Realm,你可以根据你的 Linq 的Where
参数基于一个或多个“过滤器”属性。通过 Realm.Add(filterObject, true)
更新此 RealmObject
过滤器,您基于该对象的查询也会更新
Realm queries are live, in the sense that they will continue to represent the current state of the database.
结果是快速过滤,在任何 UI 搜索例程中都非常有效。
示例模型:
public class ARealmClass : RealmObject
{
public int Key { get; set; }
public string KeyString { get; set; }
}
public class ARealmClassFilter : RealmObject
{
[PrimaryKey]
public int Key { get; set; }
public int FilterKeyBy { get; set; }
}
用一些测试数据填充一个 Realm
var realm = Realm.GetInstance();
var all = realm.All<ARealmClass>();
if (all.Count() == 0)
{
realm.Write(() =>
{
for (int i = 0; i < 1000; i++)
{
var obj = new ARealmClass { Key = i, KeyString = i.ToString() };
realm.Add(obj);
}
});
}
动态实时查询示例:
var realm = Realm.GetInstance();
var all = realm.All<ARealmClass>();
Console.WriteLine(all.Count());
var filterItem = new ARealmClassFilter { Key = 1, FilterKeyBy = 500 };
realm.Write(() =>
{
realm.Add(filterItem);
});
var filtered = all.Where(_ => _.Key > filterItem.FilterKeyBy);
Console.WriteLine(filtered.Count());
realm.Write(() =>
{
filterItem.FilterKeyBy = 750;
realm.Add(filterItem, true);
});
Console.WriteLine(filtered.Count());
输出:
2017-04-24 11:53:20.376 ios_build_foo[24496:3239020] 1000
2017-04-24 11:53:20.423 ios_build_foo[24496:3239020] 499
2017-04-24 11:53:20.425 ios_build_foo[24496:3239020] 249
注意:引用文本@ https://realm.io/docs/xamarin/latest/api/linqsupport.html
关于c# - Realm + Xamarin 表单更新查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43594320/