c# - 通过 IDs 集合查询对象的 Realm
问题描述
是否有任何方法可以通过 Id 的集合查找对象列表?
像java的代码一样:
realm.where(Foo.class).in("id", ids).findAll();
目前我有以下代码:
public interface IKeyedEntity
{
string Id { get; set; }
}
public class RealmServiceWrapper<T> where T: RealmObject, IKeyedEntity
{
public List<T> Get(List<string> ids)
{
return _db.Realm.All<T>().Where(a => ids.Contains(a.Id)).ToList();
}
}
但这仍然不起作用,因为ids.Contains(a.Id)
.Net Realm 不支持
c# 中是否存在任何替代.in("id", ids)
方法?
解决方案
在编写以下扩展名后,我已经解决了我的问题:
using Realms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ReLife.Services.RealmRelated.RealmExtensions
{
public static class IQueryableExtensions
{
public static IQueryable<T> In<T>(this IQueryable<T> source, string propertyName, List<string> objList) where T : RealmObject
{
var query = string.Join(" OR ", objList.Select(i => $"{propertyName} == '{i}'"));
var rez = source.Filter(query);
return rez;
}
public static IQueryable<T> In<T>(this IQueryable<T> source, string propertyName, List<int> objList) where T : RealmObject
{
var query = string.Join(" OR ", objList.Select(i => $"{propertyName} == {i}"));
var rez = source.Filter(query);
return rez;
}
}
}
这样的扩展使我能够编写以下内容:
public IQueryable<T> Get(List<string> ids, string idPropertyName = "Id")
{
return _db.Realm.All<T>().In(idPropertyName,ids);
}
更复杂的方式,但工作得更快更好:
public static class MyQueryableExtensions
{
public static IQueryable<T> In<T, TProp>(this IQueryable<T> source,
Expression<Func<T, TProp>> propSelector, IEnumerable<TProp> values)
{
var @params = propSelector.Parameters;
var propAcc = propSelector.Body;
Expression body = Expression.Constant(false, typeof(bool));
foreach (var v in values)
body = Expression.OrElse(body,
Expression.Equal(propAcc,
Expression.Constant(v, typeof(TProp))));
var lambda = Expression.Lambda<Func<T, bool>>(body, @params);
return source.Where(lambda);
}
}
使用示例:
_db.Realm.All<T>().In((a)=>a.Id, ids);
推荐阅读
- python - 如何在python中将复数四舍五入到小数点后2位?
- c# - WebRequest: Content-Type = text/plain;charset=iso-8859-1 : '底层连接已关闭:连接意外关闭。'
- ruby-on-rails - 在 Rails 中 ModelA.transaction do ..end 和 ModelB.transaction do ..end 有什么区别?
- python - 在 Python 中使用 AND 条件查找两个模式之间的字符串
- python - 在 tkinter 中集成绘图会给出更新 idletasks 错误
- sql-server - 我如何改变;A;B;C; 到('A','B','C')?
- docker - mariadb + wordpress 与 docker 的连接错误
- javascript - 在子组件道具上使用父道具
- python - 如何过滤 Python 列表同时保持过滤值为零
- java - 为特定问题添加评论