To query, filter, and sort data in a realm, use the Realm query engine. There are two ways to use the query engine with the .NET SDK:
Debería usar la sintaxis LINQ para las consultas siempre que sea posible, ya que se alinea con las convenciones de .NET.
Nota
Acerca de los ejemplos de esta página
Los ejemplos de esta página utilizan un conjunto de datos simple para una aplicación de lista de tareas. Los dos tipos de objetos Realm son Project
y Task. Un Task tiene un nombre, el nombre del asignado y una marca de finalización. También hay un número arbitrario para la prioridad (cuanto más alto, más importante) y un recuento de minutos dedicados a trabajar en él. Un Project tiene cero o más Tasks.
See the schema for these two classes, Project and Task, below:
public partial class Items : IRealmObject { [] [] public ObjectId Id { get; set; } = ObjectId.GenerateNewId(); public string Name { get; set; } public string Assignee { get; set; } public bool IsComplete { get; set; } public int Priority { get; set; } public int ProgressMinutes { get; set; } } public partial class Project : IRealmObject { [] [] public ObjectId ID { get; set; } = ObjectId.GenerateNewId(); public string Name { get; set; } public IList<Items> Items { get; } }
Query with LINQ
El motor de consultas de Realm implementa LINQ estándar sintaxis.
There are several operators available to filter a Realm collection with LINQ. Filters work by evaluating an operator expression for every object in the collection being filtered. If the expression resolves to true, realm includes the object in the results collection.
Una expresión consiste en uno de los siguientes:
The name of a property of the object currently being evaluated
An operator
A value of any type used by realm (string, date, number, boolean, etc.)
Nota
El SDK de Realm .NET no soporta actualmente todos los operadores LINQ. Consulta la sección Operadores LINQ no soportados para obtener una lista de aquellos operadores no soportados.
Operadores de comparación
Comparaciones de valores
Operador | Descripción |
|---|---|
== | Evaluates to |
> | Evaluates to |
>= | Evaluates to |
< | Devuelve |
<= | Se evalúa como |
!= | Evaluates to |
Ejemplo
The following example uses the query engine's comparison operators to:
Encuentre tareas de alta prioridad comparando el valor de la propiedad
prioritycon un número umbral, por encima del cual la prioridad puede considerarse alta.Find just-started or short-running tasks by seeing if the
progressMinutesproperty falls within a certain range.Find unassigned tasks by finding tasks where the
assigneeproperty is equal tonull.Find tasks assigned to specific teammates Ali or Jamie by seeing if the
assigneeproperty is in a list of names.
var highPri = items.Where(i => i.Priority > 5); var quickItems = items.Where(i => i.ProgressMinutes >= 1 && i.ProgressMinutes < 15); var unassignedItems = items.Where(i => i.Assignee == null); var AliOrJamieItems = items.Where(i => i.Assignee == "Ali" || i.Assignee == "Jamie");
Operadores lógicos
You can use the logical operators listed in the following table to make compound predicates:
Operador | Descripción |
|---|---|
&& | Se evalúa como |
! | Negates the result of the given expression. |
|| | Evaluates to |
Ejemplo
We can use the query language's logical operators to find all of Ali's completed tasks. That is, we find all tasks where the assignee property value is equal to 'Ali' AND the isComplete property value is true:
var completedItemsForAli = items .Where(i => i.Assignee == "Ali" && i.IsComplete);
Operadores de String
Puedes comparar valores string utilizando los operadores de string enumerados en la siguiente tabla. Los comodines tipo regex permiten mayor flexibilidad en la búsqueda.
Operador | Descripción |
|---|---|
| Se evalúa como |
EndsWith | Evaluates to |
Like | Evaluates to
For example, the wildcard string "d?g" matches "dog", "dig", and "dug", but not "ding", "dg", or "a dog". |
Equals | Evaluates to |
Contains | Evalúa como |
string.IsNullOrEmpty | Evaluates to |
Ejemplo
Los siguientes ejemplos utilizan los operadores de cadena del motor de consulta para encontrar tareas:
// Note: In each of the following examples, you can replace the // Where() method with First(), FirstOrDefault(), // Single(), SingleOrDefault(), // Last(), or LastOrDefault(). // Get all items where the Assignee's name starts with "E" or "e" var ItemssStartWithE = items.Where(i => i.Assignee.StartsWith("E", StringComparison.OrdinalIgnoreCase)); // Get all items where the Assignee's name ends wth "is" // (lower case only) var endsWith = items.Where(t => t.Assignee.EndsWith("is", StringComparison.Ordinal)); // Get all items where the Assignee's name contains the // letters "ami" in any casing var itemsContains = items.Where(i => i.Assignee.Contains("ami", StringComparison.OrdinalIgnoreCase)); // Get all items that have no assignee var null_or_empty = items.Where(i => string.IsNullOrEmpty(i.Assignee));
Importante
Comparaciones de casos
When evaluating strings, the second parameter in all functions except Like must be either StringComparison.OrdinalIgnoreCase or StringComparison.Ordinal. For the Like() method, the second parameter is a boolean value (where "true" means "case sensitive").
Full Text Search
Puede usar LINQ para consultar propiedades con índices de búsqueda de texto completo (FTS). Para ello, utilice QueryMethods.FullTextSearch. Los siguientes ejemplos consultan el Person.Biography campo:
// Find all people with "scientist" and "Nobel" in their biography var scientists = realm.All<Person>() .Where(p => QueryMethods.FullTextSearch(p.Biography, "scientist Nobel")); // Find all people with "scientist" in their biography, but not "physics" var scientistsButNotPhysicists = realm.All<Person>() .Where(p => QueryMethods.FullTextSearch(p.Biography, "scientist -physics"));
Unsupported LINQ Operators
The following LINQ operators are not currently supported by the Realm .NET SDK:
Categoría | Operadores no compatibles |
|---|---|
Concatenation |
|
Grouping |
|
Partitioning |
|
Projection |
|
Sets |
|
Query with Realm Query Language
You can also use the Realm Query Language (RQL) to query realms. RQL is a string-based query language used to access the query engine. When using RQL, you use the Filter() method:
var elvisProjects = projects.Filter("Items.Assignee == $0", "Elvis");
Importante
Dado que LINQ permite la comprobación de errores de consultas en tiempo de compilación, debería usarlo en lugar de RQL en la mayoría de los casos. Si necesita funciones que superen las capacidades actuales de LINQ, como la agregación, utilice RQL.
Aggregate Operators
Los operadores de agregación recorren una colección y la reducen a un único valor. Ten en cuenta que las agregaciones utilizan el método filtro(), que puede utilizarse para crear consultas más complejas actualmente no soportadas por el proveedor LINQ. Filter() admite las cláusulas SORT y DISTINCT además de filtro.
For more information on the available aggregate operators, refer to the Realm Query Language aggregate operator reference.
The following examples show different ways to aggregate data:
// Get all projects with an average Item priorty > 5: var avgPriority = projects.Filter( "Items.@avg.Priority > $0", 5); // Get all projects where all Items are high-priority: var highPriProjects = projects.Filter( "Items.@min.Priority > $0", 5); // Get all projects with long-running Items: var longRunningProjects = projects.Filter( "Items.@sum.ProgressMinutes > $0", 100);
Full Text Search
You can use RQL to query on properties that have Full-Text Search Indexes (FTS) on them. To query these properties, use the TEXT operator. The following example queries the Person.Biography field:
// Find all people with "scientist" and "Nobel" in their biography var filteredScientists = realm.All<Person>() .Filter("Biography TEXT $0", "scientist Nobel"); // Find all people with "scientist" in their biography, but not "physics" var filteredScientistsButNotPhysicists = realm.All<Person>() .Filter("Biography TEXT $0", "scientist -physics");
Ordene los resultados del query
A sort operation allows you to configure the order in which Realm returns queried objects. You can sort based on one or more properties of the objects in the results collection.
Realm solo garantiza un orden consistente de resultados cuando los resultados están ordenados.
Ejemplo
El siguiente código ordena los proyectos por nombre en orden alfabético inverso (es decir, orden "descendente").
var projectsSorted = projects.OrderByDescending(p => p.Name);