Xamarin 表单,分组领域

Xamarin Forms, Grouping Realm

我正在使用 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,我也有一个这样的分组class...

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<Participant>)....

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 模式类型

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

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