我想按以下方式获取记录

SearchResult.condition为null,然后从Person中获取所有行

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

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

 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条件。你能帮我吗?

最佳答案

您可以缩短为:

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

关于c# - 如何在一行中编写以下lambda表达式?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25685934/

10-16 05:57