是否存在通过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();
}
}
但是,由于.Net Realm不支持ids.Contains(a.Id)
,因此仍然无法正常工作
c#中是否存在.in("id", ids)
方法的替代方法?
答案 0 :(得分:1)
写完以下扩展名后,我已经解决了问题:
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);