fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5.  
  6. public class Test
  7. {
  8. public static void Main()
  9. {
  10. var parameter = Expression.Parameter(typeof(Answer), "a");
  11.  
  12. var answers = new List<Answer>
  13. {
  14. new Answer { Property1 = "foo", Property2 = "bar" },
  15. new Answer { Property1 = "foo", Property2 = "baz" },
  16. };
  17.  
  18. for (var i = 1; i <= 2; ++i) {
  19. var propertyValue = Expression.MakeMemberAccess(parameter, typeof(Answer).GetProperty("Property" + i));
  20. var predicate = Expression.Equal(propertyValue, Expression.Constant("foo"));
  21. var lambda = (Func<Answer, bool>)Expression.Lambda(predicate, parameter).Compile();
  22.  
  23. Console.WriteLine("Searching Property" + i + " for the value 'foo':");
  24. foreach (var a in answers.Where(lambda)) {
  25. Console.WriteLine(a);
  26. }
  27. }
  28. }
  29. }
  30.  
  31. class Answer {
  32. public string Property1 { get; set; }
  33. public string Property2 { get; set; }
  34.  
  35. public override string ToString() {
  36. return string.Format("{0} {1}", Property1, Property2);
  37. }
  38. }
Success #stdin #stdout 0.06s 37552KB
stdin
Standard input is empty
stdout
Searching Property1 for the value 'foo':
foo bar
foo baz
Searching Property2 for the value 'foo':