使用列表中的任何项目过滤 IQueryable
Filter IQueryable with any item from the list
所以我有一个数据库,我正在尝试向 QueryBuilder 添加一个方法,它将 return 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
});
}
}
你可以使用这个:
public QueryBuilder WithName(List<string> names)
{
if (name.Any())
{
query = query.Where(x => names.Contains(x.Name));
return this;
}
else
{
return this;
}
}
所以我有一个数据库,我正在尝试向 QueryBuilder 添加一个方法,它将 return 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
});
}
}
你可以使用这个:
public QueryBuilder WithName(List<string> names)
{
if (name.Any())
{
query = query.Where(x => names.Contains(x.Name));
return this;
}
else
{
return this;
}
}