fork download
  1. using System;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4.  
  5. public class Program
  6. {
  7. public static void Main()
  8. {
  9. var someClass = new SomeClass
  10. {
  11. PropertyOne = "Value1",
  12. PropertyTwo = "Value2",
  13. PropertyThree = "Value3",
  14. PropertyFour = 4,
  15. };
  16. var props = new string[] { "PropertyOne", "PropertyTwo", "PropertyFour"};
  17. var keyFactoryExp = CreateExpression<SomeClass>(props);
  18. var keyFactory = keyFactoryExp.Compile();
  19. Console.WriteLine(keyFactory(someClass));
  20. }
  21.  
  22.  
  23. static Expression<Func<T, string>> CreateExpression<T>(string[] props)
  24. {
  25. var par = Expression.Parameter(typeof(T));
  26. return Expression.Lambda<Func<T, string>>(Expression.Call(typeof(string), "Join", Type.EmptyTypes, Expression.Constant("|"),
  27. Expression.NewArrayInit(typeof(object), props.Select(prop => Expression.Convert(Expression.Property(par, prop), typeof(object))).ToArray())), par);
  28. }
  29.  
  30. class SomeClass
  31. {
  32. public string PropertyOne { get; set; }
  33. public string PropertyTwo { get; set; }
  34. public string PropertyThree { get; set; }
  35. public int PropertyFour { get; set; }
  36. }
  37. }
Success #stdin #stdout 0.11s 30388KB
stdin
Standard input is empty
stdout
Value1|Value2|4