Home > Back-end >  Filter IQueryable with any item from the list
Filter IQueryable with any item from the list

Time:12-29

So I have a DB and I am trying to add a method to a QueryBuilder that will return IQueryable like this:

WHERE
student.Name == "Alan" OR student.Name == "Zoe" OR student.Name == "X" OR ...

I have a list of names that can be any size.

The code looks like this:

public class QueryBuilder
{
    private SudentData context;
    private IQueryable<Students> query;

    public QueryBuilder(StudentData context)
    {
        context = context;
        query = context.Students;
    }

    public QueryBuilder WithDateFrom(DateTime date)
    {
        query = query.Where(x => x.Created >= date);
        return this;
    }

    public QueryBuilder WithName(List<string> names)
    {
        if (name.Any())
        {
            //Missing query
            return this;   
        }
        else
        {
            return this;
        }
    }

    public IQueryable<StudentDataModel> Build()
    {
        return query.Select(x => new StudentDataModel()
        {
            Name = x.Name,
            DateTo = x.DateTo,
            DateFrom = x.DateFrom
        });
    }
}

CodePudding user response:

You could use this:

public QueryBuilder WithName(List<string> names)
{
    if (name.Any())
    {
        query = query.Where(x => names.Contains(x.Name));
        return this;
    }
    else
    {
        return this;
    }
}
  • Related