fork(3) download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6.  
  7. public class Test
  8. {
  9. public static IEnumerable<T> SelectItems<T>(IEnumerable<T> items, string propName, string value)
  10. {
  11. IEnumerable<PropertyInfo> props;
  12. if (!string.IsNullOrEmpty(propName))
  13. props = new PropertyInfo[] { typeof(T).GetProperty(propName) };
  14. else
  15. props = typeof(T).GetProperties();
  16. props = props.Where(x => x != null && x.PropertyType == typeof(string));
  17. Expression lastExpr = null;
  18. ParameterExpression paramExpr = Expression.Parameter(typeof(T), "x");
  19. ConstantExpression valueExpr = Expression.Constant(value);
  20. foreach(var prop in props)
  21. {
  22. var propExpr = GetPropertyExpression(prop, paramExpr, valueExpr);
  23. if (lastExpr == null)
  24. lastExpr = propExpr;
  25. else
  26. lastExpr = Expression.MakeBinary(ExpressionType.Or, lastExpr, propExpr);
  27. }
  28. if (lastExpr == null)
  29. return new T[] {};
  30. var filterExpr = Expression.Lambda(lastExpr, paramExpr);
  31. return items.Where<T>((Func<T, bool>) filterExpr.Compile());
  32. }
  33.  
  34. private static Expression GetPropertyExpression(PropertyInfo prop, ParameterExpression paramExpr, ConstantExpression valueExpr)
  35. {
  36. var memberAcc = Expression.MakeMemberAccess(paramExpr, prop);
  37. var containsMember = typeof(string).GetMethod("Contains");
  38. return Expression.Call(memberAcc, containsMember, valueExpr);
  39. }
  40.  
  41. class TestClass
  42. {
  43. public string SomeProp { get; set; }
  44. public string SomeOtherProp { get; set; }
  45. }
  46.  
  47. public static void Main()
  48. {
  49. var data = new TestClass[] {
  50. new TestClass() { SomeProp = "AAA", SomeOtherProp = "BBB" },
  51. new TestClass() { SomeProp = "BBB", SomeOtherProp = "CCC" },
  52. new TestClass() { SomeProp = "CCC", SomeOtherProp = "AAA" },
  53. };
  54. var result = SelectItems(data, "", "A");
  55. foreach(var item in result)
  56. Console.WriteLine(item.SomeProp);
  57. }
  58. }
Success #stdin #stdout 0.09s 35480KB
stdin
Standard input is empty
stdout
AAA
CCC