我正在尝试获取一些数据,但是我不知道如何在linq中执行此操作,这就是我正在尝试执行的操作
from so in db.Operations
where ((opType!= "0" ? so.Operation == int.Parse(opType) : false)
&& (idState!=0 ? so.State == idState : false)
&& (start != null ? so.StartDate == start : false)
&& (end !=null ? so.EndDate == end : false))
select so
optype是一个Int,
idState是一个Int,
结束是一个日期时间,
开始是一个业余时间
我想做的是,如果这些不为null,则将它们添加到查询函数中,以便我可以将所有数据汇总在一起
例如:在C#代码中
if((opType!= "0")
where (so.Operation == int.Parse(opType)
if(idState!=0)
where (so.Operation == int.Parse(opType) && so.State == idState
.......
因此,如果该值不为null,则该sql查询中的该句子(TRUE部分,我不想使用false部分)将其添加到where,以便我可以搜索所有非null或0的参数
最佳答案
不太清楚您到底想要什么,但是可以尝试一下:
var query = db.Operations.AsQueryable();
if (opType != null && opType != "0")
query = query.Where(x => x.Operation == int.Parse(opType);
if (idState != 0)
query = query.Where(x => x.State == idState);
if (start != null) // assuming that start is of type DateTime? otherwise use DateTime.MinValue
query = query.Where(x => x.StartDate.Date == start); // maybe >= is more appropriate
if (end != null) // also DateTime? assumed
query = query.Where(x => x.EndDate.Date == end); // maybe <= is more appropriate
var result = query.ToList(); // e.g. could also do an foreach, depending what you want to do
这种方法的诀窍是先建立查询。在使用
.ToList()
或foreach
枚举列表之前,不会枚举查询。实际上,这应该产生相同的结果:
from so in db.Operations
where ((opType != null && opType!= "0" ? so.Operation == int.Parse(opType) : true)
&& (idState!=0 ? so.State == idState : true)
&& (start != null ? so.StartDate.Date == start : true)
&& (end !=null ? so.EndDate.Date == end : true))
select so
关于linq - 帮助linq查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2405452/