I was thinking about this after recently reading about the new Null Conditional Operators in C# 6.0. So here is my code that I am currently working on...     if (!string.IsNullOrWhiteSpace(question2Answer))    {        stringbuild.Append($ and ProdUsers = {Regex.Match(question2Answer, @\d+).Value});    }    if (!string.IsNullOrWhiteSpace(question3Answer))    {        stringbuild.Append($ and ProdFullyOnline = '{(int)Enum.Parse(typeof(YesNo), question3Answer, true)}');    }    if (!string.IsNullOrWhiteSpace(question4Answer))    {        stringbuild.Append($ and ProdMultiCurrency = '{(int)Enum.Parse(typeof(YesNo), question4Answer, true)}');    }    if (!string.IsNullOrWhiteSpace(question5Answer))    {        stringbuild.Append($ and ProdPrice <= {question5Answer});    }As you can see, it is fairly repetitive. So my question, is would there be a better way of checking whether questionXAnswer is null or not and then using the not null value on the string builder. And it would be nice to use the new null conditional operators with C# 6.0, if possible. The main reason for me posting this however, is to solve the repetition problem if possible. And obviously, any other ways I could improve this would be appreciated too!
Constructing query conditions from answers that may be null
c#;null
Since you are doing the same operation over and over, you can put your strings in an array or list and use a mapping function.For example://this struct makes it easy to initialize the list of valuespublic struct Tuple{  public String Value;  public String InterpolatedValue;  public Tuple(string val, string def)  {    Value = val;    InterpolatedValue = def;  }}//dummy answers to the questionsstring question2Answer = aaa;string question3Answer = bbb;string question4Answer = ;string question5Answer = ddd;//initialize a list of answer/interpolated answer stringsList<Tuple> list = new List<Tuple>(){  new Tuple(question2Answer, $ and ProdUsers = {question2Answer}),  new Tuple(question3Answer, $ and ProdFullyOnline = '{question3Answer}'),  new Tuple(question4Answer, $ and ProdMultiCurrency = '{question4Answer}'),  new Tuple(question5Answer, $ and ProdPrice <= {question5Answer}),};//loop over list, checking for non empty answer//this line and the next takes the place of almost all of your original codeIEnumerable<string> tempList= list.Select(t => (string.IsNullOrWhiteSpace(t.Value) ? string.Empty : (t.DefaultValue)));//concat results into a single stringstring text = string.Join(, tempList);Console.WriteLine(text);Outputs:  and ProdUsers = aaa and ProdFullyOnline = 'bbb' and ProdPrice <= dddI had to add some boilerplate code to make the example work, but I think one gets the idea...