gpt4 book ai didi

c# - LINQ查询参数可以为空

转载 作者:太空宇宙 更新时间:2023-11-03 17:36:48 25 4
gpt4 key购买 nike

我在数据库中有2个重要的日期字段。

startTime和goTime

我喜欢创建其中一个参数可能为空的自定义查询,请参见我的示例

public List<Type> GetAll( DateTime startTime, DateTime goTime )
{
List<Type> getResultBetween =

(from i in DB.TABLENAME
where i.startTime >= startTime && i.goTime == ANYTHING
select i).ToList();
return getResultBetween;
}


所以现在的目标是,即使没有定义goTime,我也可以达到给定的startTime。
如果我定义goTime并让Starttime为空,它也应该工作。抢断应该让我全力以赴。

谢谢

最佳答案

尝试使用空值类型,并显式建立查询,例如:

public List<Type> GetAll(DateTime? startTime, DateTime? goTime )
{
IQueryable<Type> query = DB.TABLENAME;
if (startTime != null)
{
query = query.Where(i => i.startTime >= startTime.Value);
}
if (goTime != null)
{
query = query.Where(i => i.goTime == goTime.Value);
}
return query.ToList();
}

关于c# - LINQ查询参数可以为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1624631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com