2014-09-05 31 views
1

我想获取记录如下如何在一行中编写以下lambda表达式?

SearchResult.condition为null,则来自获取所有行人士

如果SearchResult.condition是假的,然后取行,其中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条件表达式非空值。你可以帮我吗?

+0

你想'condition.Value'的价值在表达时或创建表达式的计算来算?我也猜测这是更大问题的一部分,那是什么问题? – flindeberg 2014-09-05 13:29:35

回答

2

你可以缩短为:

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

我忘了在@Eren上投票了 – captainsac 2015-04-30 07:22:23

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); 
} 

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

+0

感谢您的回复Jon。但条件就是一切。我必须调用一个通用方法来先查找结果记录的计数,然后再调用可重用方法来获取与此条件匹配的所有记录。 – captainsac 2014-09-05 12:49:42

相关问题