Skip to content

Instantly share code, notes, and snippets.

@leekelleher
Created November 21, 2017 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leekelleher/9b874b2a615cb12927acd6fedbef75bd to your computer and use it in GitHub Desktop.
Save leekelleher/9b874b2a615cb12927acd6fedbef75bd to your computer and use it in GitHub Desktop.
Ditto `ToList` processor
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Our.Umbraco.Ditto
{
public class ToListAttribute : DittoProcessorAttribute
{
public override object ProcessValue()
{
if (typeof(IList).IsAssignableFrom(Context.PropertyDescriptor.PropertyType) && Value is IEnumerable items)
{
var targetType = Context.PropertyDescriptor.PropertyType;
var innerType = targetType.IsGenericType
? targetType.GenericTypeArguments.First()
: targetType.IsArray
? targetType.GetElementType()
: targetType;
return (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(innerType), items);
}
return Value;
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Our.Umbraco.Ditto
{
public class ToReadOnlyListAttribute : DittoProcessorAttribute
{
public override object ProcessValue()
{
var targetType = Context.PropertyDescriptor.PropertyType;
if ((targetType.IsGenericType &&
targetType.GetGenericTypeDefinition() == typeof(IReadOnlyList<>)) ||
targetType.GetInterfaces().Any(x => x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(IReadOnlyList<>)))
{
var innerType = targetType.IsGenericType
? targetType.GenericTypeArguments.First()
: targetType.IsArray
? targetType.GetElementType()
: targetType;
var genericType = typeof(List<>).MakeGenericType(innerType);
return Value is IEnumerable items
? Activator.CreateInstance(genericType, items)
: Activator.CreateInstance(genericType);
}
return Value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment