Novidades na versão 10.2.0.
Visão geral
Um dicionário Realm é uma implementação do IDictionary que tem chaves do tipo String e suporta valores de qualquer tipo Realm , exceto coleções. Para definir um dicionário, utilize uma IDictionary<string, TValue> propriedade somente para iniciar, onde TValue é qualquer um dos tipos suportados.
Tipos de Dicionário
Um dicionário de objetos pode conter objetos nulos. Da mesma forma, dicionários de tipos primitivos também podem conter valores nulos. Se você não quiser permitir valores nulos em um dicionário, use tipos não anuláveis na declaração do dicionário (por exemplo, use IDictionary<string, double> em vez de IDictionary<string, double?>). Se você estiver usando a definição do tipo de esquema mais antigo (suas classes derivam da classe base do RealmObject) ou você não tiver a anulabilidade habilitada, use o atributo [Obrigatório] se o dicionário tiver tipos de referência anuláveis, como string ou byte[].
O Realm não permite o uso de . ou $ caracteres em chaves de mapa. Você pode usar a codificação e a decodificação percentual para armazenar uma chave de mapa que contenha um desses caracteres não permitidos.
Importante
Valores anuláveis não suportados com a sincronização
Os domínios somente locais oferecem suporte a collections de valores anuláveis (opcional), mas o Sync não.
O seguinte código mostra exemplos de tipos de dicionário:
public partial class Inventory : IRealmObject { [] [] public string Id { get; set; } // The key must be of type string; the value can be // of any Realm-supported type, including objects // that inherit from RealmObject or EmbeddedObject public IDictionary<string, Plant?> Plants { get; } public IDictionary<string, bool> BooleansDictionary { get; } // Nullable types are supported in local-only // Realms, but not with Sync public IDictionary<string, int?> NullableIntDictionary { get; } public IDictionary<string, string> RequiredStringsDictionary { get; } }
Exemplo de uso
O código a seguir mostra como criar, gravar e ler a partir de dicionários usando uma query de string (RQL) ou LINQ.
var storeInventory = new Inventory() { Id = ObjectId.GenerateNewId().ToString() }; storeInventory.Plants.Add("Petunia", new Plant()); storeInventory.NullableIntDictionary.Add("random things", 7); storeInventory.RequiredStringsDictionary.Add("foo", "bar"); var storeInventory2 = new Inventory() { Id = ObjectId.GenerateNewId().ToString() }; storeInventory2.RequiredStringsDictionary.Add("foo", "Bar"); realm.Write(() => { realm.Add(storeInventory); realm.Add(storeInventory2); }); // Find all Inventory items that have "Petunia" // as a key in their Plants dictionary. var petunias = realm.All<Inventory>() .Filter("Plants.@keys == 'Petunia'"); // Find all Inventory items that have at least one value in their // IntDictionary that is larger than 5 using RQL var matchesMoreThanFive = realm.All<Inventory>() .Filter("NullableIntDictionary.@values > 5"); // Find all Inventory items where the RequiredStringsDictionary has a key // "Foo", and the value of that key contains the phrase "bar" // (case insensitive) var matches = realm.All<Inventory>() .Filter("RequiredStringsDictionary['foo'] CONTAINS[c] 'bar'"); // matches.Count() == 2 // Query the Plants dictionary of an Inventory object // for a specific plant var myStoreInventory = realm .All<Inventory>().FirstOrDefault(); var petunia = myStoreInventory.Plants.AsRealmQueryable() .Where(p => p.Name == "Petunia");
Atento às mudanças
Você pode usar o evento INotifyCollectionChanged.CollectionChanged em um dicionário para observar as alterações na collection, e o evento INotifyPropertyChanged.PropertyChanged para observar as alterações em propriedades específicas do dicionário.
No seguinte exemplo de código, temos uma classe com uma propriedade IDictionary<string, int> denominada IntDictionary. Criamos manipuladores de eventos para os eventos CollectionChanged e PropertyChanged:
var dictionary = container.IntDictionary.AsRealmCollection(); dictionary.CollectionChanged += (sender, e) => { Console.WriteLine($"Collection {sender} changed: {e.Action}"); }; dictionary.PropertyChanged += (sender, e) => { Console.WriteLine($"Property changed on {sender}: {e.PropertyName}"); };