Select version
v7.1 v7.0 v6.8 v6.7 v6.6 v6 v5 v4 v3 v2

Finding Products Present in Multiple Categories using LINQ to uCommerce

Once in a while a question turns up in the uCommerce support forum which has me stumped for while. As usual with LINQ once the solution presents itself it turns out to be quite simple, dare I say elegant?

So what was the question again? We need a way to find all products present in number of categories as specified by a customer, think search. So we only want products present in both categories A and B, but not products only present in only one or the other.

Here’s how you’d do that:

    
    
    // These are the categories our products must be present in
    string[] categoryNames = { "Software", "Support" };
     
    var query = from product in Product.All()
             where product.CategoryProductRelations.Where(x => categoryNames.Contains(x.Category.Name)).Count() == categoryNames.Count()
             select product;
    
    

The idea here is to first find all products for the categories we’re looking for. With that done we compare the number of categories found for each product with the number of categories we’re looking for (in our categoryNames array). If they match we’ve got he result we were after in the first place.

The cool thing about this query is that everything is translated to SQL behind the scene so the end result is very efficient execution of the query.

uCommerce Aps - Studsgade 29B - 8000 Aarhus C - Denmark
Phone +45 61 799 997 - Email [email protected] uCommerce logo