How can I write the following lambda expression in one line?

I want to fetch the records as follows

SearchResult.condition is null then fetch all the rows from Person

if SearchResult.condition is false then fetch the rows where PersonType column contains null value

if SearchResult.condition is true then fetch the rows where PersonType column contains non null value

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

I want to write the expression in one expression instead of using if else conditions. Can u plz help me in it?

Jon Skeet
people
quotationmark

Well you can do it with a conditional operator, but you need to specify the type of the expression tree for each lambda expression:

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;

But assuming you're going to use this with a LINQ query, you'd be much better off with something like:

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

As an aside, I'd strongly advise you to avoid writing mutable structs or using public fields.

people

See more on this question at Stackoverflow