Mike Robbins

Sitecore Developer Blog

Follow me on GitHub

Sitecore 7 Search ID Array Type Converter

This is a simple type converter that allows you to convert a collection of Sitecore IDs stored in a Lucene search index into a List.

public class ListIDConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(List<ID>))
        {
            return true;
        }
        return base.CanConvertFrom(context, sourceType);
       }
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        if (destinationType == typeof(List<string>))
        {
            return true;
        }
        return base.CanConvertTo(context, destinationType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        var scIds = new List<ID>();
        var ids = (List<string>) value;
        foreach (var id in ids)
        {
            ID scId;
            if (ID.TryParse(id, out scId))
            {
                scIds.Add(scId);
            }
        }
        return scIds;
    }
}

To use the Type converter decorate your public property with the TypeConverter in your Search Result class.

[TypeConverter(typeof(ListIDConverter))]
[IndexField("_templates")]
public List<ID> Templates { get; set; }