Search code examples
c#lambdaexpression

C# how to convert SQL query to Lambda Expression


I have a List of the following type:

public class V_Articles
{
    public string code{ get; set; }
    public string description { get; set; }
    public string shortDescription { get; set; }
}

I have a string variable containing the name of one of its properties:

string fieldName = "description" (or "code" or "shortDescription ")

Given an already populated list, is there a way to make a generic lambda expression?

List<V_Articles> list = Get_List(popolate the list);
List<V_Articles> list_2 = list.Where(k => k.{value of fieldName} == 'towel').ToList();

Solution

  • You can build the Func<> as an Expression<> tree:

    string fieldName = "description";
    string value = "towel";
    
    var k = Expression.Parameter(typeof(V_Articles), "k");
    
    var filter = Expression.Lambda<Func<V_Articles, bool>>(
        Expression.Equal(
            Expression.Property(k, fieldName), 
            Expression.Constant(value)
        ), 
        k
    );
    

    and then it depends on what exactly list is in your snippet. If it's an IQueryable<> like a DbSet<> you can use the Expression directly and execute your filter code directly on the DB

    List<V_Articles> list_2 = _context.V_Articles.Where(filter).ToList();
    

    otherwise you might need to turn the Expression into a Func first:

    List<V_Articles> list_2 = list.Where(filter.Compile()).ToList();