Filter items

Get the collection for filtering

You retrieve a collection of items by using the methods:

/// <summary>
/// Gets the first 50 items that matches the filter
/// </summary>
/// <typeparam name="T">The type of the item.</typeparam>
/// <param name="restClient">The rest client.</param>
/// <param name="expression">The LINQ expression to pass as a filter.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
public static Task<CollectionResponse<T>> GetItems<T>(this IRestClient restClient, Expression<Func<T, bool>> expression)
where T : class, ISdkItem

Filter expressions

The above methods accept an expression parameter that is automatically converted to a REST call.
These expressions are the following:

// filtering with a collection of ids
var ids = new string[] { item.Id, item2.Id };
var result = await restClient.GetItems<NewsDto>(x => ids.Contains(x.Id));
// filtering by classifications(tags, categories, custom classifications)
var result = await restClient.GetItems<NewsDto>(x => x.Tags.Contains(tag.Id));
// filtering by multiple classifications(tags, categories, custom classifications)
var result = await restClient.GetItems<NewsDto>(x => x.Tags.Contains(tag.Id) || x.Tags.Contains(tag2.Id));
// filtering classifications by inverting the filter
var result = await restClient.GetItems<NewsDto>(x => !x.Tags.Contains(tag.Id));
// string filter with StartsWtih
var result = await restClient.GetItems<NewsDto>(x => x.Title.StartsWith(subString));
// string filter with EndsWith
var result = await restClient.GetItems<NewsDto>(x => x.Title.EndsWith(subString));
// string filter with Equals
var result = await restClient.GetItems<NewsDto>(x => x.Title.Equals(otherString));
// string filter with Contains
var result = await restClient.GetItems<NewsDto>(x => x.Title.Contains(subString));
// negated string filters
var result = await restClient.GetItems<NewsDto>(x => !x.Title.StartsWith(subString));
// filtering by basic properties with equals
var result = await restClient.GetItems<NewsDto>(x => x.Id == item.Id);
// filtering by basic properties with not equals
var result = await restClient.GetItems<NewsDto>(x => x.Id != item.Id);
// filtering by greater than operator
var referenceDate = DateTime.UtcNow;
var result = await restClient.GetItems<NewsDto>(x => x.PublicationDate > referenceDate.AddHours(-24));
// filtering by less than operator
var referenceDate = DateTime.UtcNow;
var result = await restClient.GetItems<NewsDto>(x => x.PublicationDate < referenceDate.AddHours(-24));
// filtering by dynamic fields
var result = await restClient.GetItems<NewsDto>(x => x.GetValue<string>("Title") == "searchTitle");
// filtering by more complex expressions
var result = await restClient.GetItems<NewsDto>(x => ((x.Id == item.Id) || (x.Id == item2.Id)));
// filtering by related items
var result = await restClient.GetItems<NewsDtoInQuantum>(x => x.Thumbnail.Any(y => y.Title.StartsWith("Sample title", StringComparison.Ordinal) && y.Title.EndsWith(endsWithFilter, StringComparison.Ordinal)));
// filtering by a dynamic collection of taxons
var tags = new[] { Guid.NewGuid(), Guid.NewGuid()};
var allFilters = tags.Select(tag =>
{
var filter = new FilterClause()
{
FieldName = nameof(NewsDto.Tags),
FieldValue = tag.Id,
Operator = FilterClause.Operators.ContainsOr,
};
return (object)filter;
}).ToList();
var combinedFilter = new CombinedFilter()
{
Operator = CombinedFilter.LogicalOperators.Or,
ChildFilters = allFilters,
};
var args = new GetAllArgs() { Count = true, Take = pageSize, Filter = combinedFilter, Fields = new List<string>() { "Id", "Title" } };
var newsItems = await _restClient.GetItems<NewsDto>(args);

You can combine all of the above expressions in any binary operator form (&& ||).

Complex filtering

For more complex filters, an alternative method is provided on the IRestClient interface:

/// <summary>
/// Gets a collection of items.
/// </summary>
/// <typeparam name="T">The type of the item.</typeparam>
/// <param name="args">The arguments to be passed to the service.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
Task<CollectionResponse<T>> GetItems<T>(GetAllArgs args)
where T : class;

The GetAllArgs argument allows you to provide additional parameters for projection, filtering, sorting, pagination, and total count in the following way:

/// <summary>
/// The args class used for getting a collection of items.
/// </summary>
public class GetAllArgs : GetCommonArgs
{
/// <summary>
/// Gets or sets a value indicating whether to retrieve the total count of the items.
/// </summary>
public bool Count { get; set; }
/// <summary>
/// Gets or sets the order by clauses.
/// </summary>
public IList<OrderBy> OrderBy { get; set; } = new List<OrderBy>();
/// <summary>
/// Gets or sets the skip count.
/// </summary>
public int Skip { get; set; }
/// <summary>
/// Gets or sets the take count.
/// </summary>
public int Take { get; set; }
/// <summary>
/// Gets or sets the filter <see cref="Progress.Sitefinity.RestSdk.Filters.FilterClause"/> or <see cref="Progress.Sitefinity.RestSdk.Filters.CombinedFilter"/>.
/// </summary>
public object Filter { get; set; }
}
view raw GetAllArgs.cs hosted with ❤ by GitHub

Use it in the following way:

var combinedFilter = new CombinedFilter()
{
Operator = CombinedFilter.LogicalOperators.Or,
ChildFilters = new[]
{
new FilterClause()
{
FieldName = nameof(NewsDto.Title),
Operator = FilterClause.StringOperators.Contains,
FieldValue = uniqueFilter,
},
new FilterClause()
{
FieldName = nameof(NewsDto.Title),
Operator = FilterClause.StringOperators.Contains,
FieldValue = secondItemUniqueFilter,
},
},
};
var items = await restClient.GetItems<NewsDto>(new GetAllArgs()
{
Filter = combinedFilter,
Count = true,
Fields = new[] { "Id", "Title" },
OrderBy = new[] { new OrderBy() { Name = "Title", Type = OrderType.Descending } }
});

This filter expression is a hierarchical object structure of the types FilterClause and CombinedFilter

FilterClause

The operators available for the basic filter (FilterClause) are the following:

Logical operators

  • Equals - "eq"
  • Does not equal - "ne"
  • Greater than (for numbers) - "gt"
  • Less than (for numbers) - "lt"
  • Greater than or equal (for numbers) - "ge"
  • Less than or equal (for numbers) - "le"
  • Contains any of the collection - "any+or"
  • Contains all of the collection - "any+and"
  • Does not contain any of the collection - "not+(any+or)"

Specific string operators

  • Starts with - "startswith"
  • Ends with - "endswith"
  • Contains - "contains"

Example

new FilterClause()
{
FieldName = nameof(NewsDto.Title),
Operator = FilterClause.StringOperators.Contains,
FieldValue = secondItemUniqueFilter,
},
view raw FilterClause.cs hosted with ❤ by GitHub

In this example:

  • FieldName maps to the name of the custom field for the selected content type.
  • Operator maps to the logical operator
  • FieldValue maps to the value with which to execute the logical operation.

CombinedFilter

The combined filter is recursive and can contain child combined filters. The combined filter has an additional property called Operator which can have the value of And or Or which correspond to Logical AND and logical OR between the child filters.

var combinedFilter = new CombinedFilter()
{
Operator = CombinedFilter.LogicalOperators.Or,
ChildFilters = new[]
{
new FilterClause()
{
FieldName = nameof(NewsDto.Title),
Operator = FilterClause.StringOperators.Contains,
FieldValue = uniqueFilter,
},
new FilterClause()
{
FieldName = nameof(NewsDto.Title),
Operator = FilterClause.StringOperators.Contains,
FieldValue = secondItemUniqueFilter,
},
},
};

Mixed filter

The two filtering strategies can be mixed using the following method. It simplifies the usage of the filters and provides a parameter to control the pagination, ordering, total count and projection:

/// <summary>
/// Gets the first 50 items that matches the filter
/// </summary>
/// <typeparam name="T">The type of the item.</typeparam>
/// <param name="restClient">The rest client.</param>
/// <param name="expression">The LINQ expression to pass as a filter.</param>
/// <param name="args">The LINQ expression to pass as a filter.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
public static Task<CollectionResponse<T>> GetItems<T>(this IRestClient restClient, Expression<Func<T, bool>> expression, GetAllArgs args)
where T : class, ISdkItem
view raw MixedFilter.cs hosted with ❤ by GitHub

Filtering examples

Filter by translated tags

// filter translated tags in the "en" culture
var getAllArgs = new GetAllArgs()
{
Culture = "en",
};
var items = await restClient.GetItems<TagDto>(x => x.Title != null && ids.Contains(x.Id), getAllArgs);
// for custom taxonomies
var taxonType = RestClientContentTypes.GetTaxonType("Regions");
var result = await this.restClient.GetItems<TaxonDto>(x => x.Title != null && ids.Contains(x.Id), new GetAllArgs()
{
Type = taxonType,
Fields = new[] { "Id", "Title" }
});
view raw FilterTags.cs hosted with ❤ by GitHub

Filter by parent items with SDK object

// filter by parent items with sdk object
var children = await this.restClient.GetItems<SdkItem>(x => x.GetValue<string>("ParentId") == "myparentguid");
// filter by parent items with mapped object
[MappedSitefinityType("Telerik.Sitefinity.DynamicTypes.Model.Pressreleases.Child")]
public class ChildDto : SdkItem
{
public string Title { get; set; }
public string ParentId { get; set; }
}
var children = await this.restClient.GetItems<ChildDto>(x => x.ParentId =="myparentguid");

Want to learn more?

Increase your Sitefinity skills by signing up for our free trainings. Get Sitefinity-certified at Progress Education Community to boost your credentials.

Get started with Integration Hub | Sitefinity Cloud | Sitefinity SaaS

This free lesson teaches administrators, marketers, and other business professionals how to use the Integration hub service to create automated workflows between Sitefinity and other business systems.

Web Security for Sitefinity Administrators

This free lesson teaches administrators the basics about protecting yor Sitefinity instance and its sites from external threats. Configure HTTPS, SSL, allow lists for trusted sites, and cookie security, among others.

Foundations of Sitefinity ASP.NET Core Development

The free on-demand video course teaches developers how to use Sitefinity .NET Core and leverage its decoupled architecture and new way of coding against the platform.

Was this article helpful?