Norbert Norbertson
Norbert Norbertson

Reputation: 2210

C# simple way to build params list for variable number of params

I have a method that takes this parameter

params string[] additionalParameters 

I am building it like this:

qsParams = new string[] {"k=" + k, "l=" + l, "o=" + o, "s=" + s, "t=" + t, "h=" + h, "exp=" + exp };

These are url params. The problem is I only want to add parameters where the variables are not null or empty.

I can do this kind of thing:

if (string.IsNullOrEmpty(k))
{
    qsParams = new string[] {"l=" + l, "o=" + o, "s=" + s, "t=" + t, "h=" + h, "exp=" + exp };
}

But that's going to get complicated and ugly trying to handle all the different permutations of empty variables.

Can anyone suggest a simple way to add the params if there are not null? Perhaps a list that I can convert to a params []string?

Upvotes: 1

Views: 695

Answers (4)

mybirthname
mybirthname

Reputation: 18127

    public static void Main(string[] args)
    {

        List<string> parameters = new List<string>();

        string k = "a";
        string l = null;

        AddParam("k", k, parameters);
        AddParam("l", l, parameters);


        string[] result = parameters.ToArray();
    }

    public static void AddParam(string paramName, string paramValue, List<string> parameters)
    {
        if (string.IsNullOrEmpty(paramValue))
            return;

        parameters.Add(paramName + "=" + paramValue);
    }

You can try something like this.

Upvotes: 2

Dispersia
Dispersia

Reputation: 1438

Just create a dictionary with the key being the param and the value being well... the value.

Dictionary<string, string> Parameters = new Dictionary<string, string>();

Parameters.Add("k", "myKValue");
Parameters.Add("o", "myOValue");

string paramaterList = string.Join("&", Parameters.Select(x => $"{x.Key}={x.Value}"));

Only add values to the dictionary when they aren't null.

Upvotes: 0

Sefe
Sefe

Reputation: 14007

You can write a method that returns null if your variable has no value:

private string GetListValue(string prefix, string value) {
    if (String.IsNullOrEmpty(value)) {
        return null;
    }
    else {
        return prefix + value;
    }
}

You can define your raw list with this method (only using 2 values):

string[] rawList = { GetListValue("k=", k), GetListValue("l=", l) };

Then clean the list with LINQ:

string[] cleanValues = rawValues.Where(v => v != null).ToArray();

Upvotes: 1

Paviel Kraskoŭski
Paviel Kraskoŭski

Reputation: 1419

If your params are always in right order:

List<string> qsParams = new List<string>();
string[] paramNames = new string[] { "k", "l", "o", "s", "t", "h", "exp" };
for (int i = 0; i < additionalParameters.Length; i++)
{
    if (!string.IsNullOrEmpty(additionalParameters[i]))
    {
        qsParams.Add(string.Format("{0}={1}", paramNames[i], additionalParameters[i]));
    }
}

Upvotes: 0

Related Questions