Make an enumerable collection of your strings, use the linq bit to filter out the zeros, then reconnect everything together using String.Join :
var elements = new[]{baselink, sharedkey, service, period, bulletintype, includeresults, includemap, username, password}; var nonNullElements = elements.Where(e => e != null); var outputString = String.Join("&", nonNullElements);
In the event that you are actually trying to assemble a request, there are better ways.
For example, you can use HttpUtility and reflection using the following method to parse an anonymous object into a query string:
public static class ObjEx { public static string ToQueryString(this object data) { var collection = data.GetType() .GetProperties() .Aggregate( HttpUtility.ParseQueryString(string.Empty), (prev,curr) => { var val = curr.GetValue(data); var propName = curr.Name; prev.Add(propName,val.ToString()); return prev; }); return collection.ToString(); } }
then
var data = new{foo = "bar", num = 1, cat = "bad", dog = "good", needsEscaping = "Γ©\"&"}; Console.WriteLine(data.ToQueryString());
will provide you with:
foo = bar & num = 1 & cat = bad & dog = good & needsEscaping =% u00e9% 22% 26
source share