jeudi 9 janvier 2020

Linq - How to combine reflection with where and contains

I want to create a dynamic method for selecting data bei using contains in a where clause. I found a lot of information about expressions, but I can't find a combination that works.

I posted my method and I stuck at this line:

.Where(p => p.Description != null && p.Description.ToLower().Contains(lowerFilter));

What is best practice by solving the problem?

Selection Method:

public List<TEntity> GetItems(string sortBy, string sort, string? filter)
{
    IQueryable<TEntity> items = dbContext.Set<TEntity>();

    if (filter != null && filter.Length > 0)
    {
        string lowerFilter = filter.ToLower(CultureInfo.CurrentCulture);

        items = items
            .Where(p => p.Description != null && p.Description.ToLower().Contains(lowerFilter));
    }

    if (!string.IsNullOrEmpty(sortBy))
    {
        if (!string.IsNullOrEmpty(sort))
        {
            items = items.AsQueryable().OrderBy($"{sortBy} {sort}");
        }
    }

    List<TEntity> itemsList = items.ToList();

    return itemsList;
}




Aucun commentaire:

Enregistrer un commentaire