2

I have a method which I pass string and a list in to. What I'm trying to achieve is to convert the string into lambda expression property.

private someMethod(string myTypeString, List<Values> typeList)
{
    foreach(var type in typeList.Where(x => x."myTypeString" > DateTime.Now))
    {
        //do my loop
    }
}

Is there a way to do that?

user2224135
  • 57
  • 1
  • 7
  • Via reflection. – Oswald Nov 08 '16 at 10:04
  • Wh at you posted won't work. You can't have x."myTypeString". You could do something like this (x => DataTime.Parse(x.myTypeString) > DataTime.Now) – jdweng Nov 08 '16 at 10:05
  • 3
    And why not redesign the method to receive a `Predicate`? You would not need reflection you would only need to send the expression you want to apply. – jorgonor Nov 08 '16 at 10:06
  • putting the first two comments together: it can be done via reflection, maybe you get help in the question linked to by @BojanB. But you should consider runtime behaviour if you have big lists to filter by your reflection-get-thing – swe Nov 08 '16 at 10:07
  • This is not something you should be doing. It's a gigantic "code smell". One possible solution could be to send in a Func to the method instead. Reflection should be avoided when possible. – robhol Nov 08 '16 at 10:18

2 Answers2

3

You can try using Reflection:

using System.Reflection;
...

private void someMethod(string myTypeString, List<Values> typeList)
{
    PropertyInfo pi = typeof(Values)
      .GetProperty(myTypeString,
         System.Reflection.BindingFlags.Instance | 
         System.Reflection.BindingFlags.NonPublic | // private/internal/protected  
         System.Reflection.BindingFlags.Public);

    // property exists, can be read and returns DateTime
    if (null == pi)
      return; // or throw exception
    else if (!pi.CanRead)  
      return; // or throw exception 
    else if (pi.PropertyType != typeof(DateTime))
      return; // or throw exception

    foreach(var type in typeList
      .Where(x => (DateTime) (pi.GetValue(x, null)) > DateTime.Now))
    {
        //do my loop
    }
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1
  1. Create this method somewhere.
    public static object GetPropValue(object src, string propName)
    {
        return src.GetType().GetProperty(propName).GetValue(src, null);
    }
  1. Use the method in your lambda expression
    private someMethod(string myTypeString, List typeList)
    {
        foreach(var type in typeList.Where(x => (DateTime)GetPropValue(x, myTypeString) > DateTime.Now))
        {
            //do my loop
        }
    }
Oswald
  • 1,252
  • 20
  • 32