this.Items
is a list of products. Each product has a category (product.Attributes["category"]
).
I want to render a drop down list, where all the products are grouped by category. This works well, but how could I improve it? Could there be a way to not use a dictionary?
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
var groups = new Dictionary<string, List<ListItem>>();
// sort by category
foreach (ListItem product in this.Items)
{
if (!groups.ContainsKey(category))
{
groups.Add(category, new List<ListItem>());
}
groups[category].Add(product);
}
// render each category
foreach (var group in groups)
{
// <optgroup>
RenderOptionGroupBeginTag(group.Key, writer);
// each option
group.Value.ForEach(p => this.RenderListItem(p, writer));
// </optgroup>
RenderOptionGroupEndTag(writer);
}
}