Zilberman Rafael
Zilberman Rafael

Reputation: 1451

Search by string field name

I need to build Search by string field name.

For example this code:

SearchProvider.Search(records, "First", "S2");

Should be equal to:

SearchProvider.Search(records, x => x.First, "S2");

The problem: converting string to Linq lambda expression.

How I can do this?

Upvotes: 1

Views: 221

Answers (1)

Zilberman Rafael
Zilberman Rafael

Reputation: 1451

You should convert the string to lambda expression using Expression.Lambda for example:

public IQueryable<TModel> Search<TModel>(IQueryable<TModel> model, string selector, string searchFor)
{
    var param = Expression.Parameter(typeof(TModel), "x");
        var contains = Expression.Call(
            Expression.PropertyOrField(param, selector),
            "Contains", null, Expression.Constant(searchFor)
        );
        var predicate = Expression.Lambda<Func<TModel, bool>>(contains, param);

        model = model.Where(predicate);
    return model;
}

Next for fair search you should do two things:

  • Search for any object not just strings.
  • Lower all the strings.

Here is example:

public IQueryable<TModel> Search<TModel>(IQueryable<TModel> model, string selector, object searchFor)
{
    var param = Expression.Parameter(typeof(TModel), "x");
    var tostring = Expression.Call(
        Expression.PropertyOrField(param, selector),
        "ToString", null, null
        );
    var tolower = Expression.Call(
        tostring,
        "ToLower", null, null
        );
    var contains = Expression.Call(
        tolower,
        "Contains", null, Expression.Constant(searchFor)
                );
    var predicate = Expression.Lambda<Func<TModel, bool>>(contains, param);

    model = model.Where(predicate);

        return model;
}

Good luck.

Upvotes: 2

Related Questions