Guides

Line Item Visitors

Design Pattern

Represent an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Gang of Four

Reference:

Example Visitor to find all line items with an extended data value.

namespace Merchello.Examples
{
    using System.Collections.Generic;

    using Merchello.Core.Models;

    using Umbraco.Core;

    /// <summary>
    /// A line item visitor to return line items with a specific value
    /// </summary>
    public class ExtendedDataValueVistor : ILineItemVisitor
    {
        /// <summary>
        /// The extended data key.
        /// </summary>
        private readonly string _key;

        /// <summary>
        /// The exented data value.
        /// </summary>
        private readonly string _value;

        /// <summary>
        /// The resulting line items.
        /// </summary>
        private List<ILineItem> _lineItems = new List<ILineItem>();

        /// <summary>
        /// Initializes a new instance of the <see cref="ExtendedDataValueVistor"/> class.
        /// </summary>
        /// <param name="extendedDataKey">
        /// The extended data key.
        /// </param>
        /// <param name="extendedDataValue">
        /// The extended data value.
        /// </param>
        public ExtendedDataValueVistor(string extendedDataKey, string extendedDataValue)
        {
            Mandate.ParameterNotNullOrEmpty(extendedDataKey, "extendedDataKey");
            Mandate.ParameterNotNullOrEmpty(extendedDataValue, "extendedDataValue");
        }

        /// <summary>
        /// Gets the matching items.
        /// </summary>
        public IEnumerable<ILineItem> MatchingItems
        {
            get
            {
                return _lineItems;
            }
        }

        /// <summary>
        /// Visits the line item and checks for an extended data key / value.
        /// </summary>
        /// <param name="item">
        /// The item.
        /// </param>
        public void Visit(ILineItem item)
        {
            // if the key does not exist - return
            if (!item.ExtendedData.ContainsKey(_key)) return;

            var value = item.ExtendedData.GetValue(_key);

            // if the value does not match - return
            if (!value.Equals(_value)) return;

            // add the item to the result collection
            _lineItems.Add(item);
        }
    }

}

Now we can use it to find items in any LineItemCollection (Basket, WishList, Invoice, Order, Shipment)

var invoiceKey = new Guid("CEE79DA2-0214-492B-8C61-84E6E38FC80E"); // invoice key from somewhere

var invoice = MerchelloContext.Current.Services.InvoiceService.GetByKey(invoiceKey);

var visitor = new ExtendedDataValueVistor("demoKey", "demoValue");

invoice.Accept(visitor);

var matchingItems = visitor.MatchingItems;