Docs Menu

Docs HomeRealm

Sets - .NET SDK

On this page

  • Overview
  • Set Types
  • Usage Example
  • Data Binding

New in version 10.2.0.

A Realm set, like the C# HashSet<>, is an implementation of ICollection<> and IEnumerable<>. It supports values of any Realm type except collections. To define a set, use a getter-only ISet<TValue> property, where TValue is any of the supported types.

Deleting an object from the database will remove it from any sets in which it existed. Therefore, a set of objects will never contain null objects. However, sets of primitive types can contain null values. If you do not want to allow null values in a set, then either use non-nullable types in the set declaration (for example, use ISet<double> instead of ISet<double?>), or add the [Required] attribute if the set contains nullable reference types, such as string or byte[].

Important

Not Supported with Sync

Local-only Realm Databases support collections of nullable (optional) values, but Sync does not.

The following code shows examples of set types:

public partial class Inventory : IRealmObject
{
// A Set can contain any Realm-supported type, including
// objects that inherit from RealmObject
public ISet<Plant> PlantSet { get; }
public ISet<double> DoubleSet { get; }
// Nullable types are supported in local-only
// Realms, but not with Sync
public ISet<int?> NullableIntsSet { get; }
// For C# types that are implicitly nullable, you can
// use the [Required] attribute to prevent storing null values
[Required]
public ISet<string> RequiredStrings { get; }
}

The following code shows how to create, write to, and read from Sets.

var inventory = new Inventory();
inventory.PlantSet.Add(new Plant() { Name = "Prickly Pear" });
inventory.DoubleSet.Add(123.45);
realm.Write(() =>
{
realm.Add<Inventory>(inventory);
});
// convert the Plant Set to an IQueryable and apply a filter
var pricklyPear = inventory.PlantSet.AsRealmQueryable()
.Where(p => p.Name == "Prickly Pear");
// Alternatively, apply a filter directly on the Plant Set
var pricklyPearPlants = inventory.PlantSet
.Filter("Name == 'Prickly Pear'");
// Find all Inventory items that have at least one value in their
// DoubleSet that is larger than 5
var moreThan100 = realm.All<Inventory>()
.Filter("DoubleSet.@values > 100");

Like other Realm collections, ISet implements INotifyCollectionChanged, so you can use it in data-binding scenarios (for example, when watching for changes).

←  Dictionaries - .NET SDKRealmValue - .NET SDK →
Share Feedback
© 2023 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.