【问题标题】:How can I write the following lambda expression in one line?如何在一行中编写以下 lambda 表达式?
【发布时间】:2014-09-05 12:29:13
【问题描述】:

我想获取如下记录

SearchResult.condition 为 null 然后从 Person

获取所有行

如果 SearchResult.condition 为 false,则获取 PersonType 列包含空值的行

如果 SearchResult.condition 为真,则获取 PersonType 列包含非空值的行

 struct SearchResult
 {
     public string Name;
     public bool? condition; 
 }

 Expression<Func<Person, bool>> expression;
 if(condition==null)
 {
     expression= (a =>
        (SearchResult.Name==null || a.Name == SearchResult.Name)
     );
 } 

else if(condition.Value == true)
 {
    expression= (a =>
    (SearchResult.Name==null || a.Name == SearchResult.Name)
    && a.PersonType != null)
 } 
 else if(condition.Value == false)
 {
    expression= (a =>
    (SearchResult.Name==null || a.Name == SearchResult.Name)
    && a.PersonType == null)
 }

我想将表达式写在一个表达式中,而不是使用 if else 条件。你能帮我吗?

【问题讨论】:

  • 您希望condition.Value 的值在计算表达式时计数还是在创建表达式时计数?我也猜这是一个更大问题的一部分,那是什么问题?

标签: c# sql linq lambda expression


【解决方案1】:

可以使用条件运算符来做到这一点,但你需要为每个 lambda 表达式指定表达式树的类型:

var expression = condition == null
    ? (Expression<Func<Person, bool>>) a => SearchResult.Name == null || 
                                            a.Name == SearchResult.Name
    : condition.Value
    ? (Expression<Func<Person, bool>>) a => (SearchResult.Name == null || 
                                             a.Name == SearchResult.Name) &&
                                            a.PersonType != null
    : (Expression<Func<Person, bool>>) a => (SearchResult.Name == null || 
                                             a.Name == SearchResult.Name) &&
                                            a.PersonType == null;

但假设您打算将其与 LINQ 查询一起使用,您最好使用以下内容:

var query = foo.Where(a => SearchResult.Name == null ||
                           a.Name == SearchResult.Name);
if (condition != null)
{
    query = condition.Value ? query.Where(a => a.PersonType != null)
                            : query.Where(a => a.PersonType == null);
}

顺便说一句,我强烈建议您避免编写可变结构或使用公共字段。

【讨论】:

  • 感谢乔恩的回复。但条件就是一切。我必须先调用一个通用方法来找出结果记录的数量,然后再调用可重用的方法来获取与此条件匹配的所有记录。
【解决方案2】:

你可以缩短为:

expression = a => 
    (SearchResult.Name == null || a.Name == SearchResult.Name) && 
    (SearchResult.condition == null || Search.condition == (a.PersonType != null));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2011-10-31
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多