gpt4 book ai didi

c# - 具有空参数的 Linq 不起作用

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

我不明白为什么这个查询不起作用,你能帮我吗?

 public static IEnumerable<SelectListItem> MyList(int? id, string name="")
{
var list =db.Entity
.Where(p=>
(name==null? p.Name !=null : p.Name==name) &&
(id.hasValue || p.Id==id)
.Select(n=>new SelectListItem()
{
Text=n.Name,
Value=n.Id.ToString()
}).ToList();
return list;
}

当两个参数都为空时,我想得到完整的列表!!但是当两个参数都为空时,我得到一个空列表。

该片段代码来自一个大方法,其中包含多个类似这样的查询。

最佳答案

如果我对您的理解正确,您不想在值为 null 时执行过滤。那么你应该写:

.Where(p=>
(name == null || p.Name == name) &&
(id == null || p.Id == id)

并且您应该更改函数的签名以将参数 name 的默认值设置为 null 而不是空字符串。

public static IEnumerable<SelectListItem> MyList(int? id, string name = null)

关于c# - 具有空参数的 Linq 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35239504/

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