【问题标题】:Filter IQueryable with any item from the list使用列表中的任何项目过滤 IQueryable
【发布时间】:2021-12-28 13:46:33
【问题描述】:

所以我有一个数据库,我正在尝试向 QueryBuilder 添加一个方法,该方法将返回 IQueryable,如下所示:

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

我有一个可以是任意大小的名称列表。

代码如下所示:

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
        });
    }
}

【问题讨论】:

    标签: c# .net entity-framework iqueryable


    【解决方案1】:

    你可以用这个:

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

    【讨论】:

      猜你喜欢
      • 2020-01-02
      • 1970-01-01
      • 2013-05-27
      • 2013-04-21
      • 1970-01-01
      • 2012-11-20
      • 2022-01-08
      • 1970-01-01
      • 2020-07-08
      相关资源
      最近更新 更多