如何在一行中编写以下lambda表达式?

时间:2014-09-05 12:29:13

标签: c# sql linq lambda expression

我想按如下方式获取记录

SearchResult.condition 为空,然后从

获取所有行

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

如果 SearchResult.condition 为true,则获取 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条件。你能帮助我吗?

2 个答案:

答案 0 :(得分:5)

可以使用条件运算符来完成它,但你需要为每个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);
}

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

答案 1 :(得分:3)

你可以缩短为:

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