Search code examples
c#linqmultidimensional-arrayfiltering

How to filter the records with sub-children


I want to filter products by subCategories.

This is my JSON for products:

{
    "id": 1,
    "name": "Adidas Quick Force",
    "price": 3500.00,
    "pictureUrl": "/adidas_shoe-1.png",
    "category": {
        "id": 1,
        "name": "FootBall",
        "subCategories": [
            {
                "id": 1,
                "name": "FootBall Boots"
            },
            {
                "id": 2,
                "name": "FootBalls"
            }
        ]
    }
}

I can filter by Category by this method:

public static IQueryable<Product> FilterCategory(this IQueryable<Product> products, string name)
{
    if (name != null)
    {
        return products.Where(e => (e.Category.Name == name) );
    }
    return products;
}

I tried this but it gives an error:

public static IQueryable<Product> FilterCategory(this IQueryable<Product> products, string name)
{
    if (name != null)
    {
        return products.Where(e => (e.Category.subCategories.Name == name) ); // error is here
    }
    return products;
}

Solution

  • Note that SubCategories is an array/list, you can't directly access the Name property.

    Instead, you can look for .Any() with a predicate to filter the product containing the nested object with matching name in the subCategories array.

    return products.Where(e => e.Category.subCategories.Any(x => x.Name == name));