Linq动态或条件
本文关键字:条件 动态 Linq | 更新日期: 2023-09-27 18:13:38
我有一个这样的用户表,
Id(int)
Name(string),
State_Id(Int64),
Country_Id(Int64),
MobileNumber(String),
email(String),
identity(String)
Role_Id
Disable(Boolean)
Identity列的值以逗号分隔,例如(,mole in hand, mole in face,)。这些值是预定义的,
现在我有一个这样的请求,
class UserRequest
{
public String RoleName{get;set;}
public String CountryName{get;set;}
publi String StateName{get;set;}
publi IList<String> identityLst{get;set;}
}
使用我想要的请求形成一个查询。
public IList<User> GetUser(UserRequest req)
{
IQueryable<User> query=dataContext.user.where(a=>!a.isdisable)
if(String.IsNullOrEmpty(req.RoleName))
{
query=from qu in query
from role in datacontext.role.where(a=>a.id==qu.role.id)
where role.name==req.RoleName
select qu;
}
if(String.IsNullOrEmpty(req.CountryName))
{
query=from qu in query
from country in datacontext.country.where(a=>a.id==qu.country.id)
where country.name==req.CountryName
select qu;
}
if(String.IsNullOrEmpty(req.StateName))
{
query=from qu in query
from state in datacontext.state.where(a=>a.id==qu.state.id)
where state.name==req.StateName
select qu;
}
if(req.identityLst!=null)
{
/////Here I need a query with or condition, Is it possible.
/////for example if identity List have 3 value. i need a 3 or condition
}
}
请帮我解决这个问题。如果identityLst有10个值,我将访问DB 10次。
不要在服务器上进行查询,而是在运行时进行一些后过滤。
public IList<User> GetUser(UserRequest req){
//remove the [if(req.identityLst!=null)] part
}
public bool ContainsIdentity(IList<string> x, IList<string> y)
{
if( x == null || y == null ) return false;
return x.Any(test => y.Contains(test));
}
var users = GetUser(req).ToList();
var filtered = users.Where( u => ContainsIdentity(u.identity.Split(','), req.identityLst ));