Search code examples
umbracowhere-clauseumbraco7

How to apply Where condition on Umbraco Collection


I want to apply where condition on Umbraco Collection.

Code:

var workList = CurrentPage.work.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
var workCollection = Umbraco.Content(workList);
@foreach (var item in workCollection.Where("productImage!=\"\"").Skip((i - 1) * iterationCount).Take(iterationCount))

But I always get data without filter.
ProductImage is media picker enter image description here enter image description here


Solution

  • If you want to stick to dynamic object, you should try:

    var workList = CurrentPage.work.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
    var workCollection = Umbraco.Content(workList);
    @foreach (var item in workCollection.Where("productImage != null && productImage != string.Empty").Skip((i - 1) * iterationCount).Take(iterationCount)) { ... }
    

    Personally, I prefer to deal with strongly typed objects, so another solution may be:

    var workList = CurrentPage.work.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
    var workCollection = Umbraco.TypedContent(workList);
    @foreach (IPublishedContent item in workCollection.Where(x => x.HasValue("productImage")).Skip((i - 1) * iterationCount).Take(iterationCount)) { ... }
    

    For more informations check: https://our.umbraco.org/documentation/reference/templating/mvc/querying.

    You can also check a package called Umbraco Core Property Value Converters: https://our.umbraco.org/projects/developer-tools/umbraco-core-property-value-converters/ which is automatically converting some data type values into easily accessed objects / lists etc. E.g. media picker value is returned as IPublishedContent model and you can access it's properties directly from the returned value.