Created
November 21, 2017 13:41
-
-
Save leekelleher/9b874b2a615cb12927acd6fedbef75bd to your computer and use it in GitHub Desktop.
Ditto `ToList` processor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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