AbleCommerce 7 how to sort a collection of products

by Joe Payne 18. January 2012 23:16

Introduction

Often times you find yourself working with collections of products while programming in AbleCommerce 7.  But, now you need to sort those products on a specific field and you’re not sure how.

Well it’s incredibly easy if you use the AbleCommerce object class ProductCollection.  The ProductCollection class has a convenient sort method that works on any field.

Remember that the example variable _ResultProducts is a ProductCollection object.  This technique does not work when using List<Product>

// sort the results
CommerceBuilder.Common.GenericComparer _MyComparer = new GenericComparer("Price", GenericComparer.SortDirection.ASC);
_ResultProducts.Sort(_MyComparer);

 

If you haven’t noticed yet, AbleCommerce search methods don’t always use ProductCollection as the return object.  Sometimes it’s a List<Product>.  If you need to sort a List<Product>, just copy the items to a ProductCollection object using a foreach() loop like this:

List<Product> _OldProducts = new List<Product>();
ProductCollection _SortableProducts = new ProductCollection();
// POPULATE YOUR _OldProducts //
...
// Now copy the products to a sortable collection
foreach (Product _Product in _OldProducts)
{
    _SortableProducts.Add(_Product);
}
 
// sort the results
CommerceBuilder.Common.GenericComparer _MyComparer = new GenericComparer("Price", GenericComparer.SortDirection.ASC);
_ResultProducts.Sort(_MyComparer);

Tags: ,

AC7 Articles

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Month List