//The MIT License (MIT)
//http://arolibraries.codeplex.com/license
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AroLibraries.ExtensionMethods.Enumerable
{
public static class IDictionaryExt
{
public static TValue Ext_GetValueOrDefault(this IDictionary dict, TKey key)
{
TValue result;
dict.TryGetValue(key, out result);
return result;
}
///
///
///
///
///
/// var dict = new Dictionary {
/// { "Name", "Jacob" },
/// { "Age", 26 },
/// { "FavoriteColors", new[] { ConsoleColor.Blue, ConsoleColor.Green } },
/// };
/// var person = dict.ToAnonymousType(
/// new
/// {
/// Name = default(string),
/// Age = default(int),
/// FavoriteColors = default(IEnumerable),
/// Birthday = default(DateTime?),
/// });
///
///
///
///
///
///
public static T Ext_ToAnonymousType(this IDictionary dict, T anonymousPrototype)
{
// get the sole constructor
var ctor = anonymousPrototype.GetType().GetConstructors().Single();
// conveniently named constructor parameters make this all possible...
var args = from p in ctor.GetParameters()
let val = dict.Ext_GetValueOrDefault(p.Name)
select val != null && p.ParameterType.IsAssignableFrom(val.GetType()) ? (object)val : null;
return (T)ctor.Invoke(args.ToArray());
}
}
}