首页 > 解决方案 > 通过 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)方法?

标签: c#realm

解决方案


在编写以下扩展名后,我已经解决了我的问题:

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);

推荐阅读