【问题标题】:foreach with where and condition if parameter exists如果参数存在,则使用 where 和条件 foreach
【发布时间】:2018-10-04 06:05:15
【问题描述】:

我有一个大型查询,我试图使用Where 条件和参数StudentNameStudentSurname 从中获取数据,这是由用户通过搜索表单设置的。

如果StudentNameStudentSurname 有值,一切都很好,但如果其中一个没有值,那么我什么也得不到。

问题是,在这种情况下,我希望这个 foreach 循环在没有为 null 的参数的情况下获取数据。

foreach (var item in innerJoinQuery.Where(item => item.StudentName == StudentName 
                                               && item.StudentSurname  == StudentSurname)

【问题讨论】:

  • 您的意思是没有提供输入值(即StudentName为空)还是数据不存在,即item.StudentName为空?
  • 是的。当您点击搜索但未填写 StudentName 或 StudentSurname 的搜索框时。
  • 那你需要从数据库中返回所有数据吗?
  • 在这种情况下,您只需像这样验证:string.IsNullOrEmpty(StudentName) 返回布尔值
  • 是的,无论如何我都想返回数据。如果其中一个变量为空,那么 foreach 什么也不提供。但我希望它至少返回带有第二个选项的所有数据

标签: c# linq foreach


【解决方案1】:

如果搜索参数之一为空或为空,您可以放置​​一个 OR 条件以允许项目通过。比如:

innerJoinQuery.Where(item => 
    (string.IsNullOrWhiteSpace(StudentName) || item.StudentName == StudentName) 
    && 
    (string.IsNullOrWhiteSpace(StudentSurname) || item.StudentSurname  == StudentSurname)
)

【讨论】:

  • 您可以将每个or 条件放在单独的Where 函数中,这样可读性会更高
【解决方案2】:
if (!string.IsNullOrEmpty(StudentName))
    innerJoinQuery = innerJoinQuery.Where(item => item.StudentName == StudentName);

if (!string.IsNullOrEmpty(StudentSurname))
    innerJoinQuery = innerJoinQuery.Where(item => item.StudentSurname == StudentSurname);

foreach (var item in innerJoinQuery)
...

【讨论】:

  • 我发现这比 Nisargs 解决方案更干净,更易于阅读,尽管它们本质上是相同的
猜你喜欢
  • 2020-05-09
  • 1970-01-01
  • 2014-03-08
  • 2019-11-18
  • 1970-01-01
  • 2021-07-20
  • 2014-03-31
  • 2018-11-29
  • 1970-01-01
相关资源
最近更新 更多