【问题标题】:Xamarin Forms, Grouping RealmXamarin 表单,分组领域
【发布时间】:2019-03-15 16:44:39
【问题描述】:

我正在使用 Xamarin 表单(.NET 标准项目)、Realm 和 MVVM Light,我需要根据姓氏的首字母对对象列表进行分组,以便在列表视图中显示跳转列表。

我在尝试对 RealmObject 进行分组时遇到问题。我有一个这样的模型......

public class Participant : RealmObject
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string Email {get; set;}
    public string RegistrationCode {get; set;}

    //More properties skipped out for brevity
}

基于this link,我也有一个像这样的分组类...

public class Grouping<K, T> : ObservableCollection<T>
{
    public K Key { get; private set; }

    public Grouping(K key, IEnumerable<T> items)
    {
        Key = key;
        foreach (var item in items)
            this.Items.Add(item);
    }
}

在我的视图模型中,我可以像这样获取参与者(即IQueryable&lt;Participant&gt;)......

var participants = RealmInstance.All<Participant>();

我现在希望能够按姓氏的首字母对其进行分组:

var groupedParticipants = from participant in participants
                          group participant by participant.LastName.Substring(0, 1) into pGroup
                          orderby pGroup.Key
                          select new Grouping<string, Participant>(pGroup.Key, pGroup);

抛出以下异常:

System.TypeInitializationException:“Realms.RealmCollectionBase”的类型初始化程序引发了异常。 ---> System.ArgumentException: 属性类型 IGrouping 不能表示为 Realm 模式类型

我环顾四周,但找不到分组领域集的工作示例。任何帮助将不胜感激。

【问题讨论】:

    标签: xamarin xamarin.forms realm grouping


    【解决方案1】:

    Realm 不支持 Linq 的 GroupBy(或基于 Select 的投影)。

    一种解决方法是将基于领域的排序查询带到标准List,然后执行您的 Linq GroupBy。

    示例(使用 James Montemagno 的 Monkey 项目):

    var realmSort = r.All<Monkey>().OrderBy(m => m.Name).ToList();
    var sorted = from monkey in realmSort
                     orderby monkey.Name
                     group monkey by monkey.NameSort into monkeyGroup
                     select new Grouping<string, Monkey>(monkeyGroup.Key, monkeyGroup);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    相关资源
    最近更新 更多