Both helpdesk cases and Forum suggest that it is often wanted to sort products by a custom product field when products are rendered at frontend.
The example below will sort ascending by product field "MySorting". So, courtesy of Jeppe Agger:
using Dynamicweb;
using System.Collections.Generic;
using System.Linq;
namespace ProductTemplateExtender
{
[Dynamicweb.Extensibility.Subscribe(Dynamicweb.Notifications.eCommerce.ProductList.BeforePaging)]
public class EcomProductListBeforePagingObserver1 : Dynamicweb.Extensibility.NotificationSubscriber
{
public override void OnNotify(string notification, Dynamicweb.Extensibility.NotificationArgs args)
{
var myArgs = (Dynamicweb.Notifications.eCommerce.ProductList.BeforePagingArgs)args;
var sortingDict = new Dictionary<object, List<Dynamicweb.eCommerce.Products.Product>>(); // new dictionary on which you'll perform the sorting
foreach (var product in myArgs.Products) // you may want to specify type more closely than "object"
{
var fieldValue = product.GetProductFieldValue("MySorting"); // retrieve the custom field you wish to use for sorting
if (!sortingDict.ContainsKey(fieldValue))
sortingDict.Add(fieldValue, new List<Dynamicweb.eCommerce.Products.Product>()); // use List as same sorting value may appear more than once
sortingDict[fieldValue].Add(product);
}
var col = new Dynamicweb.eCommerce.Products.ProductCollection();
foreach (var item in sortingDict.OrderBy(x => x.Key)) // order the collection and add to new empty product collection
{
foreach (var product in item.Value)
col.Add(product);
}
myArgs.Products.Clear(); // clear original collection
myArgs.Products.AddRange(col, true); // pass the ordered collection to original collection
}
}
}
Regards /Snedker