linq - 帮助linq查询

标签 linq

我正在尝试获取一些数据,但是我不知道如何在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/

相关文章:

c# - 使用第一个/最早日期返回多个记录

c# - 表达式树中的 ArrayAccess 与 ArrayIndex

c# - 我想从列表中找到最接近的较大纸张尺寸

c# - 为什么没有 Linq 方法通过谓词返回不同的值?

c# - 将 SelectMany 应用于三个或更多序列

c# - 在 linq 的哪里里面

c# - 为什么我不能用 linq 迭代可以用 foreach 迭代的东西?

c# - 将 linq 扩展到实体以识别自定义方法

c# - 使用 LINQ 将嵌套循环展平为一个列表

c# - 如何在 .net 中读取具有不同层次结构的 xml 文件