using System.Collections.Generic;
using System.Linq.Expressions;
public DateTime DateOfBirth
public static class LambdaExpressionExtensions
public static string GetPropertyName<T, TProp>(this Expression<Func<T, TProp>> property)
System.Linq.Expressions.LambdaExpression lambda = (System.Linq.Expressions.LambdaExpression)property;
System.Linq.Expressions.MemberExpression memberExpression;
if (lambda.Body is System.Linq.Expressions.UnaryExpression)
System.Linq.Expressions.UnaryExpression unaryExpression = (System.Linq.Expressions.UnaryExpression)(lambda.Body);
memberExpression = (System.Linq.Expressions.MemberExpression)(unaryExpression.Operand);
memberExpression = (System.Linq.Expressions.MemberExpression)(lambda.Body);
string name = ((PropertyInfo)memberExpression.Member).Name;
public static IDictionary<string, object> FilterOutKeys<T>(this IDictionary<string, object> dictionary, params Expression<Func<T, object>>[] keyByPropertyNameExpressions)
var result = new Dictionary<string, object>(dictionary);
foreach (var exp in keyByPropertyNameExpressions ?? new Expression<Func<T, object>>[0])
var propToExclude = exp.GetPropertyName();
result.Remove(propToExclude);
public static IDictionary<string, object> KeepOnlyKeys<T>(this IDictionary<string, object> dictionary, params Expression<Func<T, object>>[] keyByPropertyNameExpressions)
var result = new Dictionary<string, object>();
foreach (var exp in keyByPropertyNameExpressions ?? new Expression<Func<T, object>>[0])
var propToInclude = exp.GetPropertyName();
if (dictionary.TryGetValue(propToInclude, out value))
result[propToInclude] = value;
public static void Main()
var config = new MapperConfiguration(cfg => {});
var mapper = config.CreateMapper();
DateOfBirth = new DateTime(1980, 10, 13)
var fieldsAndValues = mapper.Map<Dictionary<string, object>>(person)
.KeepOnlyKeys<Person>(x => x.FirstName, x => x.LastName);
if (object.ReferenceEquals(fieldsAndValues, null))
Console.WriteLine("fieldsAndValues IS null");
foreach (var kvp in fieldsAndValues)
Console.WriteLine("Key={0}, Value={1}", kvp.Key, kvp.Value);