如何仅查询RealmObject的特定属性?

时间:2017-01-07 09:41:11

标签: c# xamarin realm

例如,我有对象:

public class person : RealmObject { 
        public string firstname { get; set; }
        public string secondname { get; set; }
        public int age { get; set; }
        public string address { get; set; }
}

如何进行查询,只提供地址列表或名字+第二名?

或名字和年龄。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下内容:

var realm = Realm.GetInstance();

var addresses = realm.All<person>()
                     .ToList()
                     .Select(person => person.address)
                     .ToList();

var firstAndSecondNames = realm.All<person>()
                               .ToList()
                               .Select(person => new
                               {
                                   FirstName = person.firstName,
                                   SecondName = person.secondName
                               })
                               .ToList();

答案 1 :(得分:1)

目前,目前不支持Select ...

只要您的Select投放RealmObject,就会受到支持,但您要求的投影会将类型从RealmObject更改为其他类型且不支持:

如果您确实需要断开对象与Realm数据库的连接,您可以将基本查询转到列表(.ToList)和然后执行选择投影结果:

realm.All<Dog>().ToList().Select(dog => dog.Name);

更新

对于您的第一个+第二个名称问题,我会将其添加为RealmObject子类的只读属性。由于该属性具有自定义setter / getter,因此它不会保留在Realm数据存储中。

public class person : RealmObject
{
    public string firstname { get; set; }
    public string secondname { get; set; }
    public int age { get; set; }
    public string address { get; set; }

    public string name { get { return firstname + " " + secondname; } }
}

然后你可以做类似的事情:

var realm = Realms.Realm.GetInstance("stackoverflow.db");
var me = new person() { firstname = "Sushi", secondname = "Hangover", age = 99, address = "Local sushi bar" };
realm.Write(() => realm.Add<person>(me));
var user = realm.All<person>().Where((person p) => p.firstname == "Sushi" && p.secondname == "Hangover").FirstOrDefault();
Console.WriteLine($"{user.name} is {user.age} years old and is currently at {user.address}");

输出:

Sushi Hangover is 99 years old and is currently at Local sushi bar

UPDATE2:

如果您希望遍历返回的RealmObjects集合:

var users = realm.All<person>().Where((person p) => p.age < 40);
Console.WriteLine($"There are {users.Count()} users under 40 years of age and they are located at:");
foreach (var user in users)
{
    Console.WriteLine($"{user.firstname} is currently at {user.address}");
}