How to create a generic method to iterate through an object's fields and use it as a Where predicate?












2















I'm building a generic interface to expose selected string properties out of a class, and then I want to search for a text inside every one of those fields, to check if it's a match.



Here's my IFieldExposer interface:



using System;
using System.Collections.Generic;

public interface IFieldExposer<T>
{
IEnumerable<Func<T, string>> GetFields();
}


Now, I implement it like this in my DataClass to expose the properties I would like to iterate. Note that I'm also exposing a property from my ChildClass:



using System;
using System.Collections.Generic;

class DataClass : IFieldExposer<DataClass>
{
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
public ChildClass Child { get; set; }

public IEnumerable<Func<DataClass, string>> GetFields()
{
return new List<Func<DataClass, string>>
{
a => a.PropertyOne,
b => b.Child.PropertyThree
};
}
}

class ChildClass
{
public string PropertyThree { get; set; }
}


I've also created extension methods for IFieldExposer<T> because I want to keep it simple and be able to simply call obj.Match(text, ignoreCase) everywhere else in my code. This method should tell me if my object is a match for my text. Here's the code for the ExtensionClass, which isn't working as expected:



using System;
using System.Linq.Expressions;
using System.Reflection;

public static class ExtensionClass
{
public static bool Match<T>(this IFieldExposer<T> obj, string text, bool ignoreCase)
{
Func<bool> expression = Expression.Lambda<Func<bool>>(obj.CreateExpressionTree(text, ignoreCase)).Compile();
return expression();
}

private static Expression CreateExpressionTree<T>(this IFieldExposer<T> obj, string text, bool ignoreCase)
{
MethodInfo containsMethod = typeof(string).GetMethod("Contains", new Type { typeof(string) });

var exposedFields = obj.GetFields();

if (ignoreCase)
{
// How should I do convert these to lower too?
// exposedFields = exposedFields.Select(e => e.???.ToLower());
text = text.ToLower();
}

Expression textExp = Expression.Constant(text);
Expression orExpressions = Expression.Constant(false);

foreach (var field in exposedFields)
{
//How should I call the contains method on the string field?
Expression fieldExpression = Expression.Lambda<Func<string>>(Expression.Call(Expression.Constant(obj), field.Method)); //this doesn't work
Expression contains = Expression.Call(fieldExpression, containsMethod, textExp);
orExpressions = Expression.Or(orExpressions, contains);
}

return orExpressions;
}
}


Please check the comments in the code above. I would like to know how to convert all my string properties to lowercase (if desired) and how to call string.Contains in each one of them. I get this error when I create my fieldExpression:



Method 'System.String <GetFields>b__12_0(DataClass)' declared on type 'DataClass+<>c' cannot be called with instance of type 'DataClass'



I don't have experience working with Expression Trees. I've spent hours reading docs and other answers for similar issues but I still can't understand how to achieve what I want... I have no clue what to do now.



I'm testing this in a console app so here's the main class if you want to build it yourself:



using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main(string args)
{
var data = new DataClass
{
PropertyOne = "Lorem",
PropertyTwo = "Ipsum",
Child = new ChildClass
{
PropertyThree = "Dolor"
}
};

var dataList = new List<DataClass> { data };
var results = dataList.Where(d => d.Match("dolor", true));

}
}


EDIT



I forgot to mention that my dataList should be IQueryable and I want to execute my code in SQL, that's why I'm trying to build the expression trees myself. So it appears my example code should be:



var dataList = new List<DataClass> { data };
var query = dataList.AsQueryable();
var results = query.Where(ExtensionClass.Match<DataClass>("lorem dolor"));


while my method becomes: (I'm following @sjb-sjb's answer and changed the GetFields() method in IFieldExposer<T> to a SelectedFields property)



public static Expression<Func<T, bool>> Match<T>(string text, bool ignoreCase) where T : IFieldExposer<T>
{
ParameterExpression parameter = Expression.Parameter(typeof(T), "obj");
MemberExpression selectedFieldsExp = Expression.Property(parameter, "SelectedFields");
LambdaExpression lambda = Expression.Lambda(selectedFieldsExp, parameter).Compile();

[...]

}


And then it seems that I have to dinamically call selectedFieldsExp with Expression.Lambda. I came up with:



Expression.Lambda(selectedFieldsExp, parameter).Compile();


and that works, but I don't know how to properly call DynamicInvoke() for the lambda expression.



It throws Parameter count mismatch. if I call it without parameters and Object of type 'System.Linq.Expressions.TypedParameterExpression' cannot be converted to type 'DataClass'. if I do DynamicInvoke(parameter).



Any ideas?










share|improve this question





























    2















    I'm building a generic interface to expose selected string properties out of a class, and then I want to search for a text inside every one of those fields, to check if it's a match.



    Here's my IFieldExposer interface:



    using System;
    using System.Collections.Generic;

    public interface IFieldExposer<T>
    {
    IEnumerable<Func<T, string>> GetFields();
    }


    Now, I implement it like this in my DataClass to expose the properties I would like to iterate. Note that I'm also exposing a property from my ChildClass:



    using System;
    using System.Collections.Generic;

    class DataClass : IFieldExposer<DataClass>
    {
    public string PropertyOne { get; set; }
    public string PropertyTwo { get; set; }
    public ChildClass Child { get; set; }

    public IEnumerable<Func<DataClass, string>> GetFields()
    {
    return new List<Func<DataClass, string>>
    {
    a => a.PropertyOne,
    b => b.Child.PropertyThree
    };
    }
    }

    class ChildClass
    {
    public string PropertyThree { get; set; }
    }


    I've also created extension methods for IFieldExposer<T> because I want to keep it simple and be able to simply call obj.Match(text, ignoreCase) everywhere else in my code. This method should tell me if my object is a match for my text. Here's the code for the ExtensionClass, which isn't working as expected:



    using System;
    using System.Linq.Expressions;
    using System.Reflection;

    public static class ExtensionClass
    {
    public static bool Match<T>(this IFieldExposer<T> obj, string text, bool ignoreCase)
    {
    Func<bool> expression = Expression.Lambda<Func<bool>>(obj.CreateExpressionTree(text, ignoreCase)).Compile();
    return expression();
    }

    private static Expression CreateExpressionTree<T>(this IFieldExposer<T> obj, string text, bool ignoreCase)
    {
    MethodInfo containsMethod = typeof(string).GetMethod("Contains", new Type { typeof(string) });

    var exposedFields = obj.GetFields();

    if (ignoreCase)
    {
    // How should I do convert these to lower too?
    // exposedFields = exposedFields.Select(e => e.???.ToLower());
    text = text.ToLower();
    }

    Expression textExp = Expression.Constant(text);
    Expression orExpressions = Expression.Constant(false);

    foreach (var field in exposedFields)
    {
    //How should I call the contains method on the string field?
    Expression fieldExpression = Expression.Lambda<Func<string>>(Expression.Call(Expression.Constant(obj), field.Method)); //this doesn't work
    Expression contains = Expression.Call(fieldExpression, containsMethod, textExp);
    orExpressions = Expression.Or(orExpressions, contains);
    }

    return orExpressions;
    }
    }


    Please check the comments in the code above. I would like to know how to convert all my string properties to lowercase (if desired) and how to call string.Contains in each one of them. I get this error when I create my fieldExpression:



    Method 'System.String <GetFields>b__12_0(DataClass)' declared on type 'DataClass+<>c' cannot be called with instance of type 'DataClass'



    I don't have experience working with Expression Trees. I've spent hours reading docs and other answers for similar issues but I still can't understand how to achieve what I want... I have no clue what to do now.



    I'm testing this in a console app so here's the main class if you want to build it yourself:



    using System.Collections.Generic;
    using System.Linq;

    class Program
    {
    static void Main(string args)
    {
    var data = new DataClass
    {
    PropertyOne = "Lorem",
    PropertyTwo = "Ipsum",
    Child = new ChildClass
    {
    PropertyThree = "Dolor"
    }
    };

    var dataList = new List<DataClass> { data };
    var results = dataList.Where(d => d.Match("dolor", true));

    }
    }


    EDIT



    I forgot to mention that my dataList should be IQueryable and I want to execute my code in SQL, that's why I'm trying to build the expression trees myself. So it appears my example code should be:



    var dataList = new List<DataClass> { data };
    var query = dataList.AsQueryable();
    var results = query.Where(ExtensionClass.Match<DataClass>("lorem dolor"));


    while my method becomes: (I'm following @sjb-sjb's answer and changed the GetFields() method in IFieldExposer<T> to a SelectedFields property)



    public static Expression<Func<T, bool>> Match<T>(string text, bool ignoreCase) where T : IFieldExposer<T>
    {
    ParameterExpression parameter = Expression.Parameter(typeof(T), "obj");
    MemberExpression selectedFieldsExp = Expression.Property(parameter, "SelectedFields");
    LambdaExpression lambda = Expression.Lambda(selectedFieldsExp, parameter).Compile();

    [...]

    }


    And then it seems that I have to dinamically call selectedFieldsExp with Expression.Lambda. I came up with:



    Expression.Lambda(selectedFieldsExp, parameter).Compile();


    and that works, but I don't know how to properly call DynamicInvoke() for the lambda expression.



    It throws Parameter count mismatch. if I call it without parameters and Object of type 'System.Linq.Expressions.TypedParameterExpression' cannot be converted to type 'DataClass'. if I do DynamicInvoke(parameter).



    Any ideas?










    share|improve this question



























      2












      2








      2








      I'm building a generic interface to expose selected string properties out of a class, and then I want to search for a text inside every one of those fields, to check if it's a match.



      Here's my IFieldExposer interface:



      using System;
      using System.Collections.Generic;

      public interface IFieldExposer<T>
      {
      IEnumerable<Func<T, string>> GetFields();
      }


      Now, I implement it like this in my DataClass to expose the properties I would like to iterate. Note that I'm also exposing a property from my ChildClass:



      using System;
      using System.Collections.Generic;

      class DataClass : IFieldExposer<DataClass>
      {
      public string PropertyOne { get; set; }
      public string PropertyTwo { get; set; }
      public ChildClass Child { get; set; }

      public IEnumerable<Func<DataClass, string>> GetFields()
      {
      return new List<Func<DataClass, string>>
      {
      a => a.PropertyOne,
      b => b.Child.PropertyThree
      };
      }
      }

      class ChildClass
      {
      public string PropertyThree { get; set; }
      }


      I've also created extension methods for IFieldExposer<T> because I want to keep it simple and be able to simply call obj.Match(text, ignoreCase) everywhere else in my code. This method should tell me if my object is a match for my text. Here's the code for the ExtensionClass, which isn't working as expected:



      using System;
      using System.Linq.Expressions;
      using System.Reflection;

      public static class ExtensionClass
      {
      public static bool Match<T>(this IFieldExposer<T> obj, string text, bool ignoreCase)
      {
      Func<bool> expression = Expression.Lambda<Func<bool>>(obj.CreateExpressionTree(text, ignoreCase)).Compile();
      return expression();
      }

      private static Expression CreateExpressionTree<T>(this IFieldExposer<T> obj, string text, bool ignoreCase)
      {
      MethodInfo containsMethod = typeof(string).GetMethod("Contains", new Type { typeof(string) });

      var exposedFields = obj.GetFields();

      if (ignoreCase)
      {
      // How should I do convert these to lower too?
      // exposedFields = exposedFields.Select(e => e.???.ToLower());
      text = text.ToLower();
      }

      Expression textExp = Expression.Constant(text);
      Expression orExpressions = Expression.Constant(false);

      foreach (var field in exposedFields)
      {
      //How should I call the contains method on the string field?
      Expression fieldExpression = Expression.Lambda<Func<string>>(Expression.Call(Expression.Constant(obj), field.Method)); //this doesn't work
      Expression contains = Expression.Call(fieldExpression, containsMethod, textExp);
      orExpressions = Expression.Or(orExpressions, contains);
      }

      return orExpressions;
      }
      }


      Please check the comments in the code above. I would like to know how to convert all my string properties to lowercase (if desired) and how to call string.Contains in each one of them. I get this error when I create my fieldExpression:



      Method 'System.String <GetFields>b__12_0(DataClass)' declared on type 'DataClass+<>c' cannot be called with instance of type 'DataClass'



      I don't have experience working with Expression Trees. I've spent hours reading docs and other answers for similar issues but I still can't understand how to achieve what I want... I have no clue what to do now.



      I'm testing this in a console app so here's the main class if you want to build it yourself:



      using System.Collections.Generic;
      using System.Linq;

      class Program
      {
      static void Main(string args)
      {
      var data = new DataClass
      {
      PropertyOne = "Lorem",
      PropertyTwo = "Ipsum",
      Child = new ChildClass
      {
      PropertyThree = "Dolor"
      }
      };

      var dataList = new List<DataClass> { data };
      var results = dataList.Where(d => d.Match("dolor", true));

      }
      }


      EDIT



      I forgot to mention that my dataList should be IQueryable and I want to execute my code in SQL, that's why I'm trying to build the expression trees myself. So it appears my example code should be:



      var dataList = new List<DataClass> { data };
      var query = dataList.AsQueryable();
      var results = query.Where(ExtensionClass.Match<DataClass>("lorem dolor"));


      while my method becomes: (I'm following @sjb-sjb's answer and changed the GetFields() method in IFieldExposer<T> to a SelectedFields property)



      public static Expression<Func<T, bool>> Match<T>(string text, bool ignoreCase) where T : IFieldExposer<T>
      {
      ParameterExpression parameter = Expression.Parameter(typeof(T), "obj");
      MemberExpression selectedFieldsExp = Expression.Property(parameter, "SelectedFields");
      LambdaExpression lambda = Expression.Lambda(selectedFieldsExp, parameter).Compile();

      [...]

      }


      And then it seems that I have to dinamically call selectedFieldsExp with Expression.Lambda. I came up with:



      Expression.Lambda(selectedFieldsExp, parameter).Compile();


      and that works, but I don't know how to properly call DynamicInvoke() for the lambda expression.



      It throws Parameter count mismatch. if I call it without parameters and Object of type 'System.Linq.Expressions.TypedParameterExpression' cannot be converted to type 'DataClass'. if I do DynamicInvoke(parameter).



      Any ideas?










      share|improve this question
















      I'm building a generic interface to expose selected string properties out of a class, and then I want to search for a text inside every one of those fields, to check if it's a match.



      Here's my IFieldExposer interface:



      using System;
      using System.Collections.Generic;

      public interface IFieldExposer<T>
      {
      IEnumerable<Func<T, string>> GetFields();
      }


      Now, I implement it like this in my DataClass to expose the properties I would like to iterate. Note that I'm also exposing a property from my ChildClass:



      using System;
      using System.Collections.Generic;

      class DataClass : IFieldExposer<DataClass>
      {
      public string PropertyOne { get; set; }
      public string PropertyTwo { get; set; }
      public ChildClass Child { get; set; }

      public IEnumerable<Func<DataClass, string>> GetFields()
      {
      return new List<Func<DataClass, string>>
      {
      a => a.PropertyOne,
      b => b.Child.PropertyThree
      };
      }
      }

      class ChildClass
      {
      public string PropertyThree { get; set; }
      }


      I've also created extension methods for IFieldExposer<T> because I want to keep it simple and be able to simply call obj.Match(text, ignoreCase) everywhere else in my code. This method should tell me if my object is a match for my text. Here's the code for the ExtensionClass, which isn't working as expected:



      using System;
      using System.Linq.Expressions;
      using System.Reflection;

      public static class ExtensionClass
      {
      public static bool Match<T>(this IFieldExposer<T> obj, string text, bool ignoreCase)
      {
      Func<bool> expression = Expression.Lambda<Func<bool>>(obj.CreateExpressionTree(text, ignoreCase)).Compile();
      return expression();
      }

      private static Expression CreateExpressionTree<T>(this IFieldExposer<T> obj, string text, bool ignoreCase)
      {
      MethodInfo containsMethod = typeof(string).GetMethod("Contains", new Type { typeof(string) });

      var exposedFields = obj.GetFields();

      if (ignoreCase)
      {
      // How should I do convert these to lower too?
      // exposedFields = exposedFields.Select(e => e.???.ToLower());
      text = text.ToLower();
      }

      Expression textExp = Expression.Constant(text);
      Expression orExpressions = Expression.Constant(false);

      foreach (var field in exposedFields)
      {
      //How should I call the contains method on the string field?
      Expression fieldExpression = Expression.Lambda<Func<string>>(Expression.Call(Expression.Constant(obj), field.Method)); //this doesn't work
      Expression contains = Expression.Call(fieldExpression, containsMethod, textExp);
      orExpressions = Expression.Or(orExpressions, contains);
      }

      return orExpressions;
      }
      }


      Please check the comments in the code above. I would like to know how to convert all my string properties to lowercase (if desired) and how to call string.Contains in each one of them. I get this error when I create my fieldExpression:



      Method 'System.String <GetFields>b__12_0(DataClass)' declared on type 'DataClass+<>c' cannot be called with instance of type 'DataClass'



      I don't have experience working with Expression Trees. I've spent hours reading docs and other answers for similar issues but I still can't understand how to achieve what I want... I have no clue what to do now.



      I'm testing this in a console app so here's the main class if you want to build it yourself:



      using System.Collections.Generic;
      using System.Linq;

      class Program
      {
      static void Main(string args)
      {
      var data = new DataClass
      {
      PropertyOne = "Lorem",
      PropertyTwo = "Ipsum",
      Child = new ChildClass
      {
      PropertyThree = "Dolor"
      }
      };

      var dataList = new List<DataClass> { data };
      var results = dataList.Where(d => d.Match("dolor", true));

      }
      }


      EDIT



      I forgot to mention that my dataList should be IQueryable and I want to execute my code in SQL, that's why I'm trying to build the expression trees myself. So it appears my example code should be:



      var dataList = new List<DataClass> { data };
      var query = dataList.AsQueryable();
      var results = query.Where(ExtensionClass.Match<DataClass>("lorem dolor"));


      while my method becomes: (I'm following @sjb-sjb's answer and changed the GetFields() method in IFieldExposer<T> to a SelectedFields property)



      public static Expression<Func<T, bool>> Match<T>(string text, bool ignoreCase) where T : IFieldExposer<T>
      {
      ParameterExpression parameter = Expression.Parameter(typeof(T), "obj");
      MemberExpression selectedFieldsExp = Expression.Property(parameter, "SelectedFields");
      LambdaExpression lambda = Expression.Lambda(selectedFieldsExp, parameter).Compile();

      [...]

      }


      And then it seems that I have to dinamically call selectedFieldsExp with Expression.Lambda. I came up with:



      Expression.Lambda(selectedFieldsExp, parameter).Compile();


      and that works, but I don't know how to properly call DynamicInvoke() for the lambda expression.



      It throws Parameter count mismatch. if I call it without parameters and Object of type 'System.Linq.Expressions.TypedParameterExpression' cannot be converted to type 'DataClass'. if I do DynamicInvoke(parameter).



      Any ideas?







      c# linq linq-to-sql expression-trees iqueryable






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 26 '18 at 10:25







      Victor Brito

















      asked Nov 25 '18 at 0:51









      Victor BritoVictor Brito

      1815




      1815
























          3 Answers
          3






          active

          oldest

          votes


















          4














          Before getting to the implementation, there are some design flaws that needs to be fixed.



          First, almost all query providers (except LINQ to Object which simply compiles the lambda expressions to delegates and executes them) don't support invocation expressions and custom (unknown) methods. That's because they do not execute the expressions, but translate them to something else (SQL for instance), and translation is based on pre knowledge.



          One example of invocation expression are Func<...> delegates. So the first thing you should do is to use Expression<Func<...>> wherever you currently have Func<...>.



          Second, the query expression trees are built statically, i.e. there is no real object instance you can use to obtain the metadata, so the idea of IFieldExposer<T> won't work. You'd need a statically exposed list of expressions like this:



          class DataClass //: IFieldExposer<DataClass>
          {
          // ...

          public static IEnumerable<Expression<Func<DataClass, string>>> GetFields()
          {
          return new List<Expression<Func<DataClass, string>>>
          {
          a => a.PropertyOne,
          b => b.Child.PropertyThree
          };
          }
          }


          Then the signature of the method in question could be like this



          public static Expression<Func<T, bool>> Match<T>(
          this IEnumerable<Expression<Func<T, string>>> fields, string text, bool ignoreCase)


          with usage like this



          var dataList = new List<DataClass> { data };
          var query = dataList.AsQueryable()
          .Where(DataClass.GetFields().Match("lorem", true));


          Now the implementation. The desired expression could be built purely with Expression class methods, but I'll show you an easier (IMHO) method, which composes expression from compile time expression by replacing the parameter(s) with other expression(s).



          All you need is a small helper utility method for replacing lambda expression parameter with another expression:



          public static partial class ExpressionUtils
          {
          public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
          {
          return new ParameterReplacer { Source = source, Target = target }.Visit(expression);
          }

          class ParameterReplacer : ExpressionVisitor
          {
          public ParameterExpression Source;
          public Expression Target;
          protected override Expression VisitParameter(ParameterExpression node)
          => node == Source ? Target : base.VisitParameter(node);
          }
          }


          Internally it uses ExpressionVistor to find each instance of the passed ParameterExpression and replace it with the passed Expression.



          With this helper method, the implementation could be like this:



          public static partial class ExpressionUtils
          {
          public static Expression<Func<T, bool>> Match<T>(this IEnumerable<Expression<Func<T, string>>> fields, string text, bool ignoreCase)
          {
          Expression<Func<string, bool>> match;
          if (ignoreCase)
          {
          text = text.ToLower();
          match = input => input.ToLower().Contains(text);
          }
          else
          {
          match = input => input.Contains(text);
          }
          // T source =>
          var parameter = Expression.Parameter(typeof(T), "source");
          Expression anyMatch = null;
          foreach (var field in fields)
          {
          // a.PropertyOne --> source.PropertyOne
          // b.Child.PropertyThree --> source.Child.PropertyThree
          var fieldAccess = field.Body.ReplaceParameter(field.Parameters[0], parameter);
          // input --> source.PropertyOne
          // input --> source.Child.PropertyThree
          var fieldMatch = match.Body.ReplaceParameter(match.Parameters[0], fieldAccess);
          // matchA || matchB
          anyMatch = anyMatch == null ? fieldMatch : Expression.OrElse(anyMatch, fieldMatch);
          }
          if (anyMatch == null) anyMatch = Expression.Constant(false);
          return Expression.Lambda<Func<T, bool>>(anyMatch, parameter);
          }
          }


          The input => input.ToLower().Contains(text) or input => input.Contains(text) is our compile time match expression, which we then replace the input parameter with the body of the passed Expression<Func<T, string>> lambda expressions, with their parameter replaced with a common parameter used in the final expression. The resulting bool expressions are combined with Expression.OrElse which is the equivalent of the C# || operator (while Expression.Or is for bitwise | operator and in general should not be used with logical operations). Same btw for && - use Expression.AndAlso and not Expression.And which is for bitwise &.



          This process is pretty much the expression equivalent of the string.Replace. In case the explanations and code comments are not enough, you can step through the code and see the exact expression transformations and expression building process.






          share|improve this answer





















          • 1





            Thank you! That was a great explanation and it solves my problem :)

            – Victor Brito
            Nov 26 '18 at 23:54











          • Good answer. I wonder if it might be possible to simplify by replacing GetFields and Match with simply FieldsMatch( string text, bool ignoreCase) and return an expression right there that compares the fields to the text. That expression could then be written with a c# lamda expression using "ToLower", "Contains", and "&&", perhaps?

            – sjb-sjb
            Nov 27 '18 at 2:17











          • @sjb-sjb Sure, there are many ways/variations of this. My goal was to follow the OP design and just tweak the non working parts.

            – Ivan Stoev
            Nov 27 '18 at 7:10











          • I wonder how this code would look like if I followed down the road and made it even more generic and reusable. I mean, if the Match method had a flags enum with options like IgnoreCase, ExactMatch (the method would use the String.Contains or String.Equals depending on that), or anything else that makes sense for string comparisons...

            – Victor Brito
            Nov 29 '18 at 3:40






          • 1





            @VictorBrito The structure of building code won't change too much. Just setting the Expression<Func<string, bool>> match variable would have more ifs in the both current if branches. e.g. if (exactMatch) match = input => input == text; else match = input => input.Contains(text);, similar in the other branch. The alternative is to build match with pure Expression methods, but it's more error prone and requires more knowledge of the expressions.

            – Ivan Stoev
            Nov 29 '18 at 3:52





















          2














          There is no need to get into the complexities of dynamically creating an Expression, because you can just invoke the Func delegate directly:



          public interface IFieldExposer<T>
          {
          IEnumerable<Func<T,string>> SelectedFields { get; }
          }
          public static class FieldExposerExtensions
          {
          public static IEnumerable<Func<T,string>> MatchIgnoreCase<T>( this IEnumerable<Func<T,string>> stringProperties, T source, string matchText)
          {
          return stringProperties.Where(stringProperty => String.Equals( stringProperty( source), matchText, StringComparison.OrdinalIgnoreCase));
          }
          }

          class DataClass : IFieldExposer<DataClass>
          {
          public string PropertyOne { get; set; }
          public string PropertyTwo { get; set; }
          public ChildClass Child { get; set; }

          public IEnumerable<Func<DataClass, string>> SelectedFields {
          get {
          return new Func<DataClass, string> { @this => @this.PropertyOne, @this => @this.Child.PropertyThree };
          }
          }

          public override string ToString() => this.PropertyOne + " " + this.PropertyTwo + " " + this.Child.PropertyThree;
          }

          class ChildClass
          {
          public string PropertyThree { get; set; }
          }


          Then to use it,



          class Program
          {
          static void Main(string args)
          {
          var data = new DataClass {
          PropertyOne = "Lorem",
          PropertyTwo = "Ipsum",
          Child = new ChildClass {
          PropertyThree = "Dolor"
          }
          };
          var data2 = new DataClass {
          PropertyOne = "lorem",
          PropertyTwo = "ipsum",
          Child = new ChildClass {
          PropertyThree = "doloreusement"
          }
          };

          var dataList = new List<DataClass>() { data, data2 };
          IEnumerable<DataClass> results = dataList.Where( d => d.SelectedFields.MatchIgnoreCase( d, "lorem").Any());
          foreach (DataClass source in results) {
          Console.WriteLine(source.ToString());
          }
          Console.ReadKey();
          }
          }





          share|improve this answer
























          • That's very helpful but doesn't solve my problem. I really need to build the expression trees because my dataList is a LINQ to SQL database context... I forgot to mention that, my bad!

            – Victor Brito
            Nov 25 '18 at 17:12











          • Do you mean you want all of this to execute on the sql server?

            – sjb-sjb
            Nov 26 '18 at 2:45











          • Yes, exactly! I just edited the question with more information. Would you care to take a look, please?

            – Victor Brito
            Nov 26 '18 at 10:26



















          1














          Following up on my comment above, I think you could do it like this:



          class DataClass 
          {


          static public Expression<Func<DataClass,bool>> MatchSelectedFields( string text, bool ignoreCase)
          {
          return @this => (
          String.Equals( text, @this.PropertyOne, (ignoreCase? StringComparison.OrdinalIgnoreCase: StringComparison.Ordinal))
          || String.Equals( text, @this.Child.PropertyThree, (ignoreCase? StringComparison.OrdinalIgnoreCase: StringComparison.Ordinal))
          );
          }
          }


          Then the query is just



               Expression<Func<DataClass,bool>> match = DataClass.MatchSelectedFields( "lorem", ignoreCase);
          IEnumerable<DataClass> results = dataList.Where( d => match(d));


          I wouldn't usually post a second answer but I thought it would be useful to see how to avoid dynamic modification of Expressions.
          Caveat: I didn't actually try to compile it.






          share|improve this answer


























          • This code's useful, yes. Thank you! The only problem in my opinion is that you'd have to repeat all the string comparisons (imagine if you had like 6 properties to try to match, for instance). And you'd have to do all of it for each class that you'd like to have a "Match" method. I certainly don't need to have a generic function in my real world scenario but it's how I prefer since the same behavior could be easily repeated for other classes.

            – Victor Brito
            Nov 29 '18 at 3:35






          • 1





            Well, this would replace GetFields (returning property lambdas) with MatchSelectedFields (returning property Equals expression). For that you get to save an additional class and expression re-writing. Personally I would do it. Might want an extension method to shorten the String.Equals phrase.

            – sjb-sjb
            Nov 30 '18 at 1:10











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463755%2fhow-to-create-a-generic-method-to-iterate-through-an-objects-fields-and-use-it%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          3 Answers
          3






          active

          oldest

          votes








          3 Answers
          3






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4














          Before getting to the implementation, there are some design flaws that needs to be fixed.



          First, almost all query providers (except LINQ to Object which simply compiles the lambda expressions to delegates and executes them) don't support invocation expressions and custom (unknown) methods. That's because they do not execute the expressions, but translate them to something else (SQL for instance), and translation is based on pre knowledge.



          One example of invocation expression are Func<...> delegates. So the first thing you should do is to use Expression<Func<...>> wherever you currently have Func<...>.



          Second, the query expression trees are built statically, i.e. there is no real object instance you can use to obtain the metadata, so the idea of IFieldExposer<T> won't work. You'd need a statically exposed list of expressions like this:



          class DataClass //: IFieldExposer<DataClass>
          {
          // ...

          public static IEnumerable<Expression<Func<DataClass, string>>> GetFields()
          {
          return new List<Expression<Func<DataClass, string>>>
          {
          a => a.PropertyOne,
          b => b.Child.PropertyThree
          };
          }
          }


          Then the signature of the method in question could be like this



          public static Expression<Func<T, bool>> Match<T>(
          this IEnumerable<Expression<Func<T, string>>> fields, string text, bool ignoreCase)


          with usage like this



          var dataList = new List<DataClass> { data };
          var query = dataList.AsQueryable()
          .Where(DataClass.GetFields().Match("lorem", true));


          Now the implementation. The desired expression could be built purely with Expression class methods, but I'll show you an easier (IMHO) method, which composes expression from compile time expression by replacing the parameter(s) with other expression(s).



          All you need is a small helper utility method for replacing lambda expression parameter with another expression:



          public static partial class ExpressionUtils
          {
          public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
          {
          return new ParameterReplacer { Source = source, Target = target }.Visit(expression);
          }

          class ParameterReplacer : ExpressionVisitor
          {
          public ParameterExpression Source;
          public Expression Target;
          protected override Expression VisitParameter(ParameterExpression node)
          => node == Source ? Target : base.VisitParameter(node);
          }
          }


          Internally it uses ExpressionVistor to find each instance of the passed ParameterExpression and replace it with the passed Expression.



          With this helper method, the implementation could be like this:



          public static partial class ExpressionUtils
          {
          public static Expression<Func<T, bool>> Match<T>(this IEnumerable<Expression<Func<T, string>>> fields, string text, bool ignoreCase)
          {
          Expression<Func<string, bool>> match;
          if (ignoreCase)
          {
          text = text.ToLower();
          match = input => input.ToLower().Contains(text);
          }
          else
          {
          match = input => input.Contains(text);
          }
          // T source =>
          var parameter = Expression.Parameter(typeof(T), "source");
          Expression anyMatch = null;
          foreach (var field in fields)
          {
          // a.PropertyOne --> source.PropertyOne
          // b.Child.PropertyThree --> source.Child.PropertyThree
          var fieldAccess = field.Body.ReplaceParameter(field.Parameters[0], parameter);
          // input --> source.PropertyOne
          // input --> source.Child.PropertyThree
          var fieldMatch = match.Body.ReplaceParameter(match.Parameters[0], fieldAccess);
          // matchA || matchB
          anyMatch = anyMatch == null ? fieldMatch : Expression.OrElse(anyMatch, fieldMatch);
          }
          if (anyMatch == null) anyMatch = Expression.Constant(false);
          return Expression.Lambda<Func<T, bool>>(anyMatch, parameter);
          }
          }


          The input => input.ToLower().Contains(text) or input => input.Contains(text) is our compile time match expression, which we then replace the input parameter with the body of the passed Expression<Func<T, string>> lambda expressions, with their parameter replaced with a common parameter used in the final expression. The resulting bool expressions are combined with Expression.OrElse which is the equivalent of the C# || operator (while Expression.Or is for bitwise | operator and in general should not be used with logical operations). Same btw for && - use Expression.AndAlso and not Expression.And which is for bitwise &.



          This process is pretty much the expression equivalent of the string.Replace. In case the explanations and code comments are not enough, you can step through the code and see the exact expression transformations and expression building process.






          share|improve this answer





















          • 1





            Thank you! That was a great explanation and it solves my problem :)

            – Victor Brito
            Nov 26 '18 at 23:54











          • Good answer. I wonder if it might be possible to simplify by replacing GetFields and Match with simply FieldsMatch( string text, bool ignoreCase) and return an expression right there that compares the fields to the text. That expression could then be written with a c# lamda expression using "ToLower", "Contains", and "&&", perhaps?

            – sjb-sjb
            Nov 27 '18 at 2:17











          • @sjb-sjb Sure, there are many ways/variations of this. My goal was to follow the OP design and just tweak the non working parts.

            – Ivan Stoev
            Nov 27 '18 at 7:10











          • I wonder how this code would look like if I followed down the road and made it even more generic and reusable. I mean, if the Match method had a flags enum with options like IgnoreCase, ExactMatch (the method would use the String.Contains or String.Equals depending on that), or anything else that makes sense for string comparisons...

            – Victor Brito
            Nov 29 '18 at 3:40






          • 1





            @VictorBrito The structure of building code won't change too much. Just setting the Expression<Func<string, bool>> match variable would have more ifs in the both current if branches. e.g. if (exactMatch) match = input => input == text; else match = input => input.Contains(text);, similar in the other branch. The alternative is to build match with pure Expression methods, but it's more error prone and requires more knowledge of the expressions.

            – Ivan Stoev
            Nov 29 '18 at 3:52


















          4














          Before getting to the implementation, there are some design flaws that needs to be fixed.



          First, almost all query providers (except LINQ to Object which simply compiles the lambda expressions to delegates and executes them) don't support invocation expressions and custom (unknown) methods. That's because they do not execute the expressions, but translate them to something else (SQL for instance), and translation is based on pre knowledge.



          One example of invocation expression are Func<...> delegates. So the first thing you should do is to use Expression<Func<...>> wherever you currently have Func<...>.



          Second, the query expression trees are built statically, i.e. there is no real object instance you can use to obtain the metadata, so the idea of IFieldExposer<T> won't work. You'd need a statically exposed list of expressions like this:



          class DataClass //: IFieldExposer<DataClass>
          {
          // ...

          public static IEnumerable<Expression<Func<DataClass, string>>> GetFields()
          {
          return new List<Expression<Func<DataClass, string>>>
          {
          a => a.PropertyOne,
          b => b.Child.PropertyThree
          };
          }
          }


          Then the signature of the method in question could be like this



          public static Expression<Func<T, bool>> Match<T>(
          this IEnumerable<Expression<Func<T, string>>> fields, string text, bool ignoreCase)


          with usage like this



          var dataList = new List<DataClass> { data };
          var query = dataList.AsQueryable()
          .Where(DataClass.GetFields().Match("lorem", true));


          Now the implementation. The desired expression could be built purely with Expression class methods, but I'll show you an easier (IMHO) method, which composes expression from compile time expression by replacing the parameter(s) with other expression(s).



          All you need is a small helper utility method for replacing lambda expression parameter with another expression:



          public static partial class ExpressionUtils
          {
          public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
          {
          return new ParameterReplacer { Source = source, Target = target }.Visit(expression);
          }

          class ParameterReplacer : ExpressionVisitor
          {
          public ParameterExpression Source;
          public Expression Target;
          protected override Expression VisitParameter(ParameterExpression node)
          => node == Source ? Target : base.VisitParameter(node);
          }
          }


          Internally it uses ExpressionVistor to find each instance of the passed ParameterExpression and replace it with the passed Expression.



          With this helper method, the implementation could be like this:



          public static partial class ExpressionUtils
          {
          public static Expression<Func<T, bool>> Match<T>(this IEnumerable<Expression<Func<T, string>>> fields, string text, bool ignoreCase)
          {
          Expression<Func<string, bool>> match;
          if (ignoreCase)
          {
          text = text.ToLower();
          match = input => input.ToLower().Contains(text);
          }
          else
          {
          match = input => input.Contains(text);
          }
          // T source =>
          var parameter = Expression.Parameter(typeof(T), "source");
          Expression anyMatch = null;
          foreach (var field in fields)
          {
          // a.PropertyOne --> source.PropertyOne
          // b.Child.PropertyThree --> source.Child.PropertyThree
          var fieldAccess = field.Body.ReplaceParameter(field.Parameters[0], parameter);
          // input --> source.PropertyOne
          // input --> source.Child.PropertyThree
          var fieldMatch = match.Body.ReplaceParameter(match.Parameters[0], fieldAccess);
          // matchA || matchB
          anyMatch = anyMatch == null ? fieldMatch : Expression.OrElse(anyMatch, fieldMatch);
          }
          if (anyMatch == null) anyMatch = Expression.Constant(false);
          return Expression.Lambda<Func<T, bool>>(anyMatch, parameter);
          }
          }


          The input => input.ToLower().Contains(text) or input => input.Contains(text) is our compile time match expression, which we then replace the input parameter with the body of the passed Expression<Func<T, string>> lambda expressions, with their parameter replaced with a common parameter used in the final expression. The resulting bool expressions are combined with Expression.OrElse which is the equivalent of the C# || operator (while Expression.Or is for bitwise | operator and in general should not be used with logical operations). Same btw for && - use Expression.AndAlso and not Expression.And which is for bitwise &.



          This process is pretty much the expression equivalent of the string.Replace. In case the explanations and code comments are not enough, you can step through the code and see the exact expression transformations and expression building process.






          share|improve this answer





















          • 1





            Thank you! That was a great explanation and it solves my problem :)

            – Victor Brito
            Nov 26 '18 at 23:54











          • Good answer. I wonder if it might be possible to simplify by replacing GetFields and Match with simply FieldsMatch( string text, bool ignoreCase) and return an expression right there that compares the fields to the text. That expression could then be written with a c# lamda expression using "ToLower", "Contains", and "&&", perhaps?

            – sjb-sjb
            Nov 27 '18 at 2:17











          • @sjb-sjb Sure, there are many ways/variations of this. My goal was to follow the OP design and just tweak the non working parts.

            – Ivan Stoev
            Nov 27 '18 at 7:10











          • I wonder how this code would look like if I followed down the road and made it even more generic and reusable. I mean, if the Match method had a flags enum with options like IgnoreCase, ExactMatch (the method would use the String.Contains or String.Equals depending on that), or anything else that makes sense for string comparisons...

            – Victor Brito
            Nov 29 '18 at 3:40






          • 1





            @VictorBrito The structure of building code won't change too much. Just setting the Expression<Func<string, bool>> match variable would have more ifs in the both current if branches. e.g. if (exactMatch) match = input => input == text; else match = input => input.Contains(text);, similar in the other branch. The alternative is to build match with pure Expression methods, but it's more error prone and requires more knowledge of the expressions.

            – Ivan Stoev
            Nov 29 '18 at 3:52
















          4












          4








          4







          Before getting to the implementation, there are some design flaws that needs to be fixed.



          First, almost all query providers (except LINQ to Object which simply compiles the lambda expressions to delegates and executes them) don't support invocation expressions and custom (unknown) methods. That's because they do not execute the expressions, but translate them to something else (SQL for instance), and translation is based on pre knowledge.



          One example of invocation expression are Func<...> delegates. So the first thing you should do is to use Expression<Func<...>> wherever you currently have Func<...>.



          Second, the query expression trees are built statically, i.e. there is no real object instance you can use to obtain the metadata, so the idea of IFieldExposer<T> won't work. You'd need a statically exposed list of expressions like this:



          class DataClass //: IFieldExposer<DataClass>
          {
          // ...

          public static IEnumerable<Expression<Func<DataClass, string>>> GetFields()
          {
          return new List<Expression<Func<DataClass, string>>>
          {
          a => a.PropertyOne,
          b => b.Child.PropertyThree
          };
          }
          }


          Then the signature of the method in question could be like this



          public static Expression<Func<T, bool>> Match<T>(
          this IEnumerable<Expression<Func<T, string>>> fields, string text, bool ignoreCase)


          with usage like this



          var dataList = new List<DataClass> { data };
          var query = dataList.AsQueryable()
          .Where(DataClass.GetFields().Match("lorem", true));


          Now the implementation. The desired expression could be built purely with Expression class methods, but I'll show you an easier (IMHO) method, which composes expression from compile time expression by replacing the parameter(s) with other expression(s).



          All you need is a small helper utility method for replacing lambda expression parameter with another expression:



          public static partial class ExpressionUtils
          {
          public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
          {
          return new ParameterReplacer { Source = source, Target = target }.Visit(expression);
          }

          class ParameterReplacer : ExpressionVisitor
          {
          public ParameterExpression Source;
          public Expression Target;
          protected override Expression VisitParameter(ParameterExpression node)
          => node == Source ? Target : base.VisitParameter(node);
          }
          }


          Internally it uses ExpressionVistor to find each instance of the passed ParameterExpression and replace it with the passed Expression.



          With this helper method, the implementation could be like this:



          public static partial class ExpressionUtils
          {
          public static Expression<Func<T, bool>> Match<T>(this IEnumerable<Expression<Func<T, string>>> fields, string text, bool ignoreCase)
          {
          Expression<Func<string, bool>> match;
          if (ignoreCase)
          {
          text = text.ToLower();
          match = input => input.ToLower().Contains(text);
          }
          else
          {
          match = input => input.Contains(text);
          }
          // T source =>
          var parameter = Expression.Parameter(typeof(T), "source");
          Expression anyMatch = null;
          foreach (var field in fields)
          {
          // a.PropertyOne --> source.PropertyOne
          // b.Child.PropertyThree --> source.Child.PropertyThree
          var fieldAccess = field.Body.ReplaceParameter(field.Parameters[0], parameter);
          // input --> source.PropertyOne
          // input --> source.Child.PropertyThree
          var fieldMatch = match.Body.ReplaceParameter(match.Parameters[0], fieldAccess);
          // matchA || matchB
          anyMatch = anyMatch == null ? fieldMatch : Expression.OrElse(anyMatch, fieldMatch);
          }
          if (anyMatch == null) anyMatch = Expression.Constant(false);
          return Expression.Lambda<Func<T, bool>>(anyMatch, parameter);
          }
          }


          The input => input.ToLower().Contains(text) or input => input.Contains(text) is our compile time match expression, which we then replace the input parameter with the body of the passed Expression<Func<T, string>> lambda expressions, with their parameter replaced with a common parameter used in the final expression. The resulting bool expressions are combined with Expression.OrElse which is the equivalent of the C# || operator (while Expression.Or is for bitwise | operator and in general should not be used with logical operations). Same btw for && - use Expression.AndAlso and not Expression.And which is for bitwise &.



          This process is pretty much the expression equivalent of the string.Replace. In case the explanations and code comments are not enough, you can step through the code and see the exact expression transformations and expression building process.






          share|improve this answer















          Before getting to the implementation, there are some design flaws that needs to be fixed.



          First, almost all query providers (except LINQ to Object which simply compiles the lambda expressions to delegates and executes them) don't support invocation expressions and custom (unknown) methods. That's because they do not execute the expressions, but translate them to something else (SQL for instance), and translation is based on pre knowledge.



          One example of invocation expression are Func<...> delegates. So the first thing you should do is to use Expression<Func<...>> wherever you currently have Func<...>.



          Second, the query expression trees are built statically, i.e. there is no real object instance you can use to obtain the metadata, so the idea of IFieldExposer<T> won't work. You'd need a statically exposed list of expressions like this:



          class DataClass //: IFieldExposer<DataClass>
          {
          // ...

          public static IEnumerable<Expression<Func<DataClass, string>>> GetFields()
          {
          return new List<Expression<Func<DataClass, string>>>
          {
          a => a.PropertyOne,
          b => b.Child.PropertyThree
          };
          }
          }


          Then the signature of the method in question could be like this



          public static Expression<Func<T, bool>> Match<T>(
          this IEnumerable<Expression<Func<T, string>>> fields, string text, bool ignoreCase)


          with usage like this



          var dataList = new List<DataClass> { data };
          var query = dataList.AsQueryable()
          .Where(DataClass.GetFields().Match("lorem", true));


          Now the implementation. The desired expression could be built purely with Expression class methods, but I'll show you an easier (IMHO) method, which composes expression from compile time expression by replacing the parameter(s) with other expression(s).



          All you need is a small helper utility method for replacing lambda expression parameter with another expression:



          public static partial class ExpressionUtils
          {
          public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
          {
          return new ParameterReplacer { Source = source, Target = target }.Visit(expression);
          }

          class ParameterReplacer : ExpressionVisitor
          {
          public ParameterExpression Source;
          public Expression Target;
          protected override Expression VisitParameter(ParameterExpression node)
          => node == Source ? Target : base.VisitParameter(node);
          }
          }


          Internally it uses ExpressionVistor to find each instance of the passed ParameterExpression and replace it with the passed Expression.



          With this helper method, the implementation could be like this:



          public static partial class ExpressionUtils
          {
          public static Expression<Func<T, bool>> Match<T>(this IEnumerable<Expression<Func<T, string>>> fields, string text, bool ignoreCase)
          {
          Expression<Func<string, bool>> match;
          if (ignoreCase)
          {
          text = text.ToLower();
          match = input => input.ToLower().Contains(text);
          }
          else
          {
          match = input => input.Contains(text);
          }
          // T source =>
          var parameter = Expression.Parameter(typeof(T), "source");
          Expression anyMatch = null;
          foreach (var field in fields)
          {
          // a.PropertyOne --> source.PropertyOne
          // b.Child.PropertyThree --> source.Child.PropertyThree
          var fieldAccess = field.Body.ReplaceParameter(field.Parameters[0], parameter);
          // input --> source.PropertyOne
          // input --> source.Child.PropertyThree
          var fieldMatch = match.Body.ReplaceParameter(match.Parameters[0], fieldAccess);
          // matchA || matchB
          anyMatch = anyMatch == null ? fieldMatch : Expression.OrElse(anyMatch, fieldMatch);
          }
          if (anyMatch == null) anyMatch = Expression.Constant(false);
          return Expression.Lambda<Func<T, bool>>(anyMatch, parameter);
          }
          }


          The input => input.ToLower().Contains(text) or input => input.Contains(text) is our compile time match expression, which we then replace the input parameter with the body of the passed Expression<Func<T, string>> lambda expressions, with their parameter replaced with a common parameter used in the final expression. The resulting bool expressions are combined with Expression.OrElse which is the equivalent of the C# || operator (while Expression.Or is for bitwise | operator and in general should not be used with logical operations). Same btw for && - use Expression.AndAlso and not Expression.And which is for bitwise &.



          This process is pretty much the expression equivalent of the string.Replace. In case the explanations and code comments are not enough, you can step through the code and see the exact expression transformations and expression building process.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 27 '18 at 7:03

























          answered Nov 26 '18 at 20:09









          Ivan StoevIvan Stoev

          106k781133




          106k781133








          • 1





            Thank you! That was a great explanation and it solves my problem :)

            – Victor Brito
            Nov 26 '18 at 23:54











          • Good answer. I wonder if it might be possible to simplify by replacing GetFields and Match with simply FieldsMatch( string text, bool ignoreCase) and return an expression right there that compares the fields to the text. That expression could then be written with a c# lamda expression using "ToLower", "Contains", and "&&", perhaps?

            – sjb-sjb
            Nov 27 '18 at 2:17











          • @sjb-sjb Sure, there are many ways/variations of this. My goal was to follow the OP design and just tweak the non working parts.

            – Ivan Stoev
            Nov 27 '18 at 7:10











          • I wonder how this code would look like if I followed down the road and made it even more generic and reusable. I mean, if the Match method had a flags enum with options like IgnoreCase, ExactMatch (the method would use the String.Contains or String.Equals depending on that), or anything else that makes sense for string comparisons...

            – Victor Brito
            Nov 29 '18 at 3:40






          • 1





            @VictorBrito The structure of building code won't change too much. Just setting the Expression<Func<string, bool>> match variable would have more ifs in the both current if branches. e.g. if (exactMatch) match = input => input == text; else match = input => input.Contains(text);, similar in the other branch. The alternative is to build match with pure Expression methods, but it's more error prone and requires more knowledge of the expressions.

            – Ivan Stoev
            Nov 29 '18 at 3:52
















          • 1





            Thank you! That was a great explanation and it solves my problem :)

            – Victor Brito
            Nov 26 '18 at 23:54











          • Good answer. I wonder if it might be possible to simplify by replacing GetFields and Match with simply FieldsMatch( string text, bool ignoreCase) and return an expression right there that compares the fields to the text. That expression could then be written with a c# lamda expression using "ToLower", "Contains", and "&&", perhaps?

            – sjb-sjb
            Nov 27 '18 at 2:17











          • @sjb-sjb Sure, there are many ways/variations of this. My goal was to follow the OP design and just tweak the non working parts.

            – Ivan Stoev
            Nov 27 '18 at 7:10











          • I wonder how this code would look like if I followed down the road and made it even more generic and reusable. I mean, if the Match method had a flags enum with options like IgnoreCase, ExactMatch (the method would use the String.Contains or String.Equals depending on that), or anything else that makes sense for string comparisons...

            – Victor Brito
            Nov 29 '18 at 3:40






          • 1





            @VictorBrito The structure of building code won't change too much. Just setting the Expression<Func<string, bool>> match variable would have more ifs in the both current if branches. e.g. if (exactMatch) match = input => input == text; else match = input => input.Contains(text);, similar in the other branch. The alternative is to build match with pure Expression methods, but it's more error prone and requires more knowledge of the expressions.

            – Ivan Stoev
            Nov 29 '18 at 3:52










          1




          1





          Thank you! That was a great explanation and it solves my problem :)

          – Victor Brito
          Nov 26 '18 at 23:54





          Thank you! That was a great explanation and it solves my problem :)

          – Victor Brito
          Nov 26 '18 at 23:54













          Good answer. I wonder if it might be possible to simplify by replacing GetFields and Match with simply FieldsMatch( string text, bool ignoreCase) and return an expression right there that compares the fields to the text. That expression could then be written with a c# lamda expression using "ToLower", "Contains", and "&&", perhaps?

          – sjb-sjb
          Nov 27 '18 at 2:17





          Good answer. I wonder if it might be possible to simplify by replacing GetFields and Match with simply FieldsMatch( string text, bool ignoreCase) and return an expression right there that compares the fields to the text. That expression could then be written with a c# lamda expression using "ToLower", "Contains", and "&&", perhaps?

          – sjb-sjb
          Nov 27 '18 at 2:17













          @sjb-sjb Sure, there are many ways/variations of this. My goal was to follow the OP design and just tweak the non working parts.

          – Ivan Stoev
          Nov 27 '18 at 7:10





          @sjb-sjb Sure, there are many ways/variations of this. My goal was to follow the OP design and just tweak the non working parts.

          – Ivan Stoev
          Nov 27 '18 at 7:10













          I wonder how this code would look like if I followed down the road and made it even more generic and reusable. I mean, if the Match method had a flags enum with options like IgnoreCase, ExactMatch (the method would use the String.Contains or String.Equals depending on that), or anything else that makes sense for string comparisons...

          – Victor Brito
          Nov 29 '18 at 3:40





          I wonder how this code would look like if I followed down the road and made it even more generic and reusable. I mean, if the Match method had a flags enum with options like IgnoreCase, ExactMatch (the method would use the String.Contains or String.Equals depending on that), or anything else that makes sense for string comparisons...

          – Victor Brito
          Nov 29 '18 at 3:40




          1




          1





          @VictorBrito The structure of building code won't change too much. Just setting the Expression<Func<string, bool>> match variable would have more ifs in the both current if branches. e.g. if (exactMatch) match = input => input == text; else match = input => input.Contains(text);, similar in the other branch. The alternative is to build match with pure Expression methods, but it's more error prone and requires more knowledge of the expressions.

          – Ivan Stoev
          Nov 29 '18 at 3:52







          @VictorBrito The structure of building code won't change too much. Just setting the Expression<Func<string, bool>> match variable would have more ifs in the both current if branches. e.g. if (exactMatch) match = input => input == text; else match = input => input.Contains(text);, similar in the other branch. The alternative is to build match with pure Expression methods, but it's more error prone and requires more knowledge of the expressions.

          – Ivan Stoev
          Nov 29 '18 at 3:52















          2














          There is no need to get into the complexities of dynamically creating an Expression, because you can just invoke the Func delegate directly:



          public interface IFieldExposer<T>
          {
          IEnumerable<Func<T,string>> SelectedFields { get; }
          }
          public static class FieldExposerExtensions
          {
          public static IEnumerable<Func<T,string>> MatchIgnoreCase<T>( this IEnumerable<Func<T,string>> stringProperties, T source, string matchText)
          {
          return stringProperties.Where(stringProperty => String.Equals( stringProperty( source), matchText, StringComparison.OrdinalIgnoreCase));
          }
          }

          class DataClass : IFieldExposer<DataClass>
          {
          public string PropertyOne { get; set; }
          public string PropertyTwo { get; set; }
          public ChildClass Child { get; set; }

          public IEnumerable<Func<DataClass, string>> SelectedFields {
          get {
          return new Func<DataClass, string> { @this => @this.PropertyOne, @this => @this.Child.PropertyThree };
          }
          }

          public override string ToString() => this.PropertyOne + " " + this.PropertyTwo + " " + this.Child.PropertyThree;
          }

          class ChildClass
          {
          public string PropertyThree { get; set; }
          }


          Then to use it,



          class Program
          {
          static void Main(string args)
          {
          var data = new DataClass {
          PropertyOne = "Lorem",
          PropertyTwo = "Ipsum",
          Child = new ChildClass {
          PropertyThree = "Dolor"
          }
          };
          var data2 = new DataClass {
          PropertyOne = "lorem",
          PropertyTwo = "ipsum",
          Child = new ChildClass {
          PropertyThree = "doloreusement"
          }
          };

          var dataList = new List<DataClass>() { data, data2 };
          IEnumerable<DataClass> results = dataList.Where( d => d.SelectedFields.MatchIgnoreCase( d, "lorem").Any());
          foreach (DataClass source in results) {
          Console.WriteLine(source.ToString());
          }
          Console.ReadKey();
          }
          }





          share|improve this answer
























          • That's very helpful but doesn't solve my problem. I really need to build the expression trees because my dataList is a LINQ to SQL database context... I forgot to mention that, my bad!

            – Victor Brito
            Nov 25 '18 at 17:12











          • Do you mean you want all of this to execute on the sql server?

            – sjb-sjb
            Nov 26 '18 at 2:45











          • Yes, exactly! I just edited the question with more information. Would you care to take a look, please?

            – Victor Brito
            Nov 26 '18 at 10:26
















          2














          There is no need to get into the complexities of dynamically creating an Expression, because you can just invoke the Func delegate directly:



          public interface IFieldExposer<T>
          {
          IEnumerable<Func<T,string>> SelectedFields { get; }
          }
          public static class FieldExposerExtensions
          {
          public static IEnumerable<Func<T,string>> MatchIgnoreCase<T>( this IEnumerable<Func<T,string>> stringProperties, T source, string matchText)
          {
          return stringProperties.Where(stringProperty => String.Equals( stringProperty( source), matchText, StringComparison.OrdinalIgnoreCase));
          }
          }

          class DataClass : IFieldExposer<DataClass>
          {
          public string PropertyOne { get; set; }
          public string PropertyTwo { get; set; }
          public ChildClass Child { get; set; }

          public IEnumerable<Func<DataClass, string>> SelectedFields {
          get {
          return new Func<DataClass, string> { @this => @this.PropertyOne, @this => @this.Child.PropertyThree };
          }
          }

          public override string ToString() => this.PropertyOne + " " + this.PropertyTwo + " " + this.Child.PropertyThree;
          }

          class ChildClass
          {
          public string PropertyThree { get; set; }
          }


          Then to use it,



          class Program
          {
          static void Main(string args)
          {
          var data = new DataClass {
          PropertyOne = "Lorem",
          PropertyTwo = "Ipsum",
          Child = new ChildClass {
          PropertyThree = "Dolor"
          }
          };
          var data2 = new DataClass {
          PropertyOne = "lorem",
          PropertyTwo = "ipsum",
          Child = new ChildClass {
          PropertyThree = "doloreusement"
          }
          };

          var dataList = new List<DataClass>() { data, data2 };
          IEnumerable<DataClass> results = dataList.Where( d => d.SelectedFields.MatchIgnoreCase( d, "lorem").Any());
          foreach (DataClass source in results) {
          Console.WriteLine(source.ToString());
          }
          Console.ReadKey();
          }
          }





          share|improve this answer
























          • That's very helpful but doesn't solve my problem. I really need to build the expression trees because my dataList is a LINQ to SQL database context... I forgot to mention that, my bad!

            – Victor Brito
            Nov 25 '18 at 17:12











          • Do you mean you want all of this to execute on the sql server?

            – sjb-sjb
            Nov 26 '18 at 2:45











          • Yes, exactly! I just edited the question with more information. Would you care to take a look, please?

            – Victor Brito
            Nov 26 '18 at 10:26














          2












          2








          2







          There is no need to get into the complexities of dynamically creating an Expression, because you can just invoke the Func delegate directly:



          public interface IFieldExposer<T>
          {
          IEnumerable<Func<T,string>> SelectedFields { get; }
          }
          public static class FieldExposerExtensions
          {
          public static IEnumerable<Func<T,string>> MatchIgnoreCase<T>( this IEnumerable<Func<T,string>> stringProperties, T source, string matchText)
          {
          return stringProperties.Where(stringProperty => String.Equals( stringProperty( source), matchText, StringComparison.OrdinalIgnoreCase));
          }
          }

          class DataClass : IFieldExposer<DataClass>
          {
          public string PropertyOne { get; set; }
          public string PropertyTwo { get; set; }
          public ChildClass Child { get; set; }

          public IEnumerable<Func<DataClass, string>> SelectedFields {
          get {
          return new Func<DataClass, string> { @this => @this.PropertyOne, @this => @this.Child.PropertyThree };
          }
          }

          public override string ToString() => this.PropertyOne + " " + this.PropertyTwo + " " + this.Child.PropertyThree;
          }

          class ChildClass
          {
          public string PropertyThree { get; set; }
          }


          Then to use it,



          class Program
          {
          static void Main(string args)
          {
          var data = new DataClass {
          PropertyOne = "Lorem",
          PropertyTwo = "Ipsum",
          Child = new ChildClass {
          PropertyThree = "Dolor"
          }
          };
          var data2 = new DataClass {
          PropertyOne = "lorem",
          PropertyTwo = "ipsum",
          Child = new ChildClass {
          PropertyThree = "doloreusement"
          }
          };

          var dataList = new List<DataClass>() { data, data2 };
          IEnumerable<DataClass> results = dataList.Where( d => d.SelectedFields.MatchIgnoreCase( d, "lorem").Any());
          foreach (DataClass source in results) {
          Console.WriteLine(source.ToString());
          }
          Console.ReadKey();
          }
          }





          share|improve this answer













          There is no need to get into the complexities of dynamically creating an Expression, because you can just invoke the Func delegate directly:



          public interface IFieldExposer<T>
          {
          IEnumerable<Func<T,string>> SelectedFields { get; }
          }
          public static class FieldExposerExtensions
          {
          public static IEnumerable<Func<T,string>> MatchIgnoreCase<T>( this IEnumerable<Func<T,string>> stringProperties, T source, string matchText)
          {
          return stringProperties.Where(stringProperty => String.Equals( stringProperty( source), matchText, StringComparison.OrdinalIgnoreCase));
          }
          }

          class DataClass : IFieldExposer<DataClass>
          {
          public string PropertyOne { get; set; }
          public string PropertyTwo { get; set; }
          public ChildClass Child { get; set; }

          public IEnumerable<Func<DataClass, string>> SelectedFields {
          get {
          return new Func<DataClass, string> { @this => @this.PropertyOne, @this => @this.Child.PropertyThree };
          }
          }

          public override string ToString() => this.PropertyOne + " " + this.PropertyTwo + " " + this.Child.PropertyThree;
          }

          class ChildClass
          {
          public string PropertyThree { get; set; }
          }


          Then to use it,



          class Program
          {
          static void Main(string args)
          {
          var data = new DataClass {
          PropertyOne = "Lorem",
          PropertyTwo = "Ipsum",
          Child = new ChildClass {
          PropertyThree = "Dolor"
          }
          };
          var data2 = new DataClass {
          PropertyOne = "lorem",
          PropertyTwo = "ipsum",
          Child = new ChildClass {
          PropertyThree = "doloreusement"
          }
          };

          var dataList = new List<DataClass>() { data, data2 };
          IEnumerable<DataClass> results = dataList.Where( d => d.SelectedFields.MatchIgnoreCase( d, "lorem").Any());
          foreach (DataClass source in results) {
          Console.WriteLine(source.ToString());
          }
          Console.ReadKey();
          }
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 25 '18 at 16:14









          sjb-sjbsjb-sjb

          49428




          49428













          • That's very helpful but doesn't solve my problem. I really need to build the expression trees because my dataList is a LINQ to SQL database context... I forgot to mention that, my bad!

            – Victor Brito
            Nov 25 '18 at 17:12











          • Do you mean you want all of this to execute on the sql server?

            – sjb-sjb
            Nov 26 '18 at 2:45











          • Yes, exactly! I just edited the question with more information. Would you care to take a look, please?

            – Victor Brito
            Nov 26 '18 at 10:26



















          • That's very helpful but doesn't solve my problem. I really need to build the expression trees because my dataList is a LINQ to SQL database context... I forgot to mention that, my bad!

            – Victor Brito
            Nov 25 '18 at 17:12











          • Do you mean you want all of this to execute on the sql server?

            – sjb-sjb
            Nov 26 '18 at 2:45











          • Yes, exactly! I just edited the question with more information. Would you care to take a look, please?

            – Victor Brito
            Nov 26 '18 at 10:26

















          That's very helpful but doesn't solve my problem. I really need to build the expression trees because my dataList is a LINQ to SQL database context... I forgot to mention that, my bad!

          – Victor Brito
          Nov 25 '18 at 17:12





          That's very helpful but doesn't solve my problem. I really need to build the expression trees because my dataList is a LINQ to SQL database context... I forgot to mention that, my bad!

          – Victor Brito
          Nov 25 '18 at 17:12













          Do you mean you want all of this to execute on the sql server?

          – sjb-sjb
          Nov 26 '18 at 2:45





          Do you mean you want all of this to execute on the sql server?

          – sjb-sjb
          Nov 26 '18 at 2:45













          Yes, exactly! I just edited the question with more information. Would you care to take a look, please?

          – Victor Brito
          Nov 26 '18 at 10:26





          Yes, exactly! I just edited the question with more information. Would you care to take a look, please?

          – Victor Brito
          Nov 26 '18 at 10:26











          1














          Following up on my comment above, I think you could do it like this:



          class DataClass 
          {


          static public Expression<Func<DataClass,bool>> MatchSelectedFields( string text, bool ignoreCase)
          {
          return @this => (
          String.Equals( text, @this.PropertyOne, (ignoreCase? StringComparison.OrdinalIgnoreCase: StringComparison.Ordinal))
          || String.Equals( text, @this.Child.PropertyThree, (ignoreCase? StringComparison.OrdinalIgnoreCase: StringComparison.Ordinal))
          );
          }
          }


          Then the query is just



               Expression<Func<DataClass,bool>> match = DataClass.MatchSelectedFields( "lorem", ignoreCase);
          IEnumerable<DataClass> results = dataList.Where( d => match(d));


          I wouldn't usually post a second answer but I thought it would be useful to see how to avoid dynamic modification of Expressions.
          Caveat: I didn't actually try to compile it.






          share|improve this answer


























          • This code's useful, yes. Thank you! The only problem in my opinion is that you'd have to repeat all the string comparisons (imagine if you had like 6 properties to try to match, for instance). And you'd have to do all of it for each class that you'd like to have a "Match" method. I certainly don't need to have a generic function in my real world scenario but it's how I prefer since the same behavior could be easily repeated for other classes.

            – Victor Brito
            Nov 29 '18 at 3:35






          • 1





            Well, this would replace GetFields (returning property lambdas) with MatchSelectedFields (returning property Equals expression). For that you get to save an additional class and expression re-writing. Personally I would do it. Might want an extension method to shorten the String.Equals phrase.

            – sjb-sjb
            Nov 30 '18 at 1:10
















          1














          Following up on my comment above, I think you could do it like this:



          class DataClass 
          {


          static public Expression<Func<DataClass,bool>> MatchSelectedFields( string text, bool ignoreCase)
          {
          return @this => (
          String.Equals( text, @this.PropertyOne, (ignoreCase? StringComparison.OrdinalIgnoreCase: StringComparison.Ordinal))
          || String.Equals( text, @this.Child.PropertyThree, (ignoreCase? StringComparison.OrdinalIgnoreCase: StringComparison.Ordinal))
          );
          }
          }


          Then the query is just



               Expression<Func<DataClass,bool>> match = DataClass.MatchSelectedFields( "lorem", ignoreCase);
          IEnumerable<DataClass> results = dataList.Where( d => match(d));


          I wouldn't usually post a second answer but I thought it would be useful to see how to avoid dynamic modification of Expressions.
          Caveat: I didn't actually try to compile it.






          share|improve this answer


























          • This code's useful, yes. Thank you! The only problem in my opinion is that you'd have to repeat all the string comparisons (imagine if you had like 6 properties to try to match, for instance). And you'd have to do all of it for each class that you'd like to have a "Match" method. I certainly don't need to have a generic function in my real world scenario but it's how I prefer since the same behavior could be easily repeated for other classes.

            – Victor Brito
            Nov 29 '18 at 3:35






          • 1





            Well, this would replace GetFields (returning property lambdas) with MatchSelectedFields (returning property Equals expression). For that you get to save an additional class and expression re-writing. Personally I would do it. Might want an extension method to shorten the String.Equals phrase.

            – sjb-sjb
            Nov 30 '18 at 1:10














          1












          1








          1







          Following up on my comment above, I think you could do it like this:



          class DataClass 
          {


          static public Expression<Func<DataClass,bool>> MatchSelectedFields( string text, bool ignoreCase)
          {
          return @this => (
          String.Equals( text, @this.PropertyOne, (ignoreCase? StringComparison.OrdinalIgnoreCase: StringComparison.Ordinal))
          || String.Equals( text, @this.Child.PropertyThree, (ignoreCase? StringComparison.OrdinalIgnoreCase: StringComparison.Ordinal))
          );
          }
          }


          Then the query is just



               Expression<Func<DataClass,bool>> match = DataClass.MatchSelectedFields( "lorem", ignoreCase);
          IEnumerable<DataClass> results = dataList.Where( d => match(d));


          I wouldn't usually post a second answer but I thought it would be useful to see how to avoid dynamic modification of Expressions.
          Caveat: I didn't actually try to compile it.






          share|improve this answer















          Following up on my comment above, I think you could do it like this:



          class DataClass 
          {


          static public Expression<Func<DataClass,bool>> MatchSelectedFields( string text, bool ignoreCase)
          {
          return @this => (
          String.Equals( text, @this.PropertyOne, (ignoreCase? StringComparison.OrdinalIgnoreCase: StringComparison.Ordinal))
          || String.Equals( text, @this.Child.PropertyThree, (ignoreCase? StringComparison.OrdinalIgnoreCase: StringComparison.Ordinal))
          );
          }
          }


          Then the query is just



               Expression<Func<DataClass,bool>> match = DataClass.MatchSelectedFields( "lorem", ignoreCase);
          IEnumerable<DataClass> results = dataList.Where( d => match(d));


          I wouldn't usually post a second answer but I thought it would be useful to see how to avoid dynamic modification of Expressions.
          Caveat: I didn't actually try to compile it.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 29 '18 at 0:09

























          answered Nov 28 '18 at 23:21









          sjb-sjbsjb-sjb

          49428




          49428













          • This code's useful, yes. Thank you! The only problem in my opinion is that you'd have to repeat all the string comparisons (imagine if you had like 6 properties to try to match, for instance). And you'd have to do all of it for each class that you'd like to have a "Match" method. I certainly don't need to have a generic function in my real world scenario but it's how I prefer since the same behavior could be easily repeated for other classes.

            – Victor Brito
            Nov 29 '18 at 3:35






          • 1





            Well, this would replace GetFields (returning property lambdas) with MatchSelectedFields (returning property Equals expression). For that you get to save an additional class and expression re-writing. Personally I would do it. Might want an extension method to shorten the String.Equals phrase.

            – sjb-sjb
            Nov 30 '18 at 1:10



















          • This code's useful, yes. Thank you! The only problem in my opinion is that you'd have to repeat all the string comparisons (imagine if you had like 6 properties to try to match, for instance). And you'd have to do all of it for each class that you'd like to have a "Match" method. I certainly don't need to have a generic function in my real world scenario but it's how I prefer since the same behavior could be easily repeated for other classes.

            – Victor Brito
            Nov 29 '18 at 3:35






          • 1





            Well, this would replace GetFields (returning property lambdas) with MatchSelectedFields (returning property Equals expression). For that you get to save an additional class and expression re-writing. Personally I would do it. Might want an extension method to shorten the String.Equals phrase.

            – sjb-sjb
            Nov 30 '18 at 1:10

















          This code's useful, yes. Thank you! The only problem in my opinion is that you'd have to repeat all the string comparisons (imagine if you had like 6 properties to try to match, for instance). And you'd have to do all of it for each class that you'd like to have a "Match" method. I certainly don't need to have a generic function in my real world scenario but it's how I prefer since the same behavior could be easily repeated for other classes.

          – Victor Brito
          Nov 29 '18 at 3:35





          This code's useful, yes. Thank you! The only problem in my opinion is that you'd have to repeat all the string comparisons (imagine if you had like 6 properties to try to match, for instance). And you'd have to do all of it for each class that you'd like to have a "Match" method. I certainly don't need to have a generic function in my real world scenario but it's how I prefer since the same behavior could be easily repeated for other classes.

          – Victor Brito
          Nov 29 '18 at 3:35




          1




          1





          Well, this would replace GetFields (returning property lambdas) with MatchSelectedFields (returning property Equals expression). For that you get to save an additional class and expression re-writing. Personally I would do it. Might want an extension method to shorten the String.Equals phrase.

          – sjb-sjb
          Nov 30 '18 at 1:10





          Well, this would replace GetFields (returning property lambdas) with MatchSelectedFields (returning property Equals expression). For that you get to save an additional class and expression re-writing. Personally I would do it. Might want an extension method to shorten the String.Equals phrase.

          – sjb-sjb
          Nov 30 '18 at 1:10


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463755%2fhow-to-create-a-generic-method-to-iterate-through-an-objects-fields-and-use-it%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Ottavio Pratesi

          Tricia Helfer

          15 giugno