tags:

views:

62

answers:

2
string.Format("{0}, {1}, {2}", var1, var2, var3)

I want to apply URL Encoding on each of var1, var2, and var3. It's not an array, so I can't use Linq Aggregate to do it.

Any ideas?

I would hate to have to put brackets around each of the variable.

+7  A: 

If you don't want to put UrlEncode(...) around each argument or define a helper function, the only way is to make the implicitly created array explicit and apply the method to each element:

var args = new[] { var1, var2, var3 };
Array.ConvertAll(args, UrlEncode);
var result = string Format("{0}, {1}, {2}", args);

or

var args = new[] { var1, var2, var3 };
var result = string Format("{0}, {1}, {2}", args.Select(UrlEncode).ToArray());

or, if all you want to do is putting commas between the elements:

var result = string.Join(", ", new[] { var1, var2, var3 }.Select(UrlEncode));

Using a helper function:

var result = string.Format("{0}, {1}, {2}", UrlEncodeAll(var1, var2, var3));

or

var result = string.Join(", ", UrlEncodeAll(var1, var2, var3));

where

string[] UrlEncodeAll(params string[] args)
{
    Array.ConvertAll(args, UrlEncode);
    return args;
}
dtb
+1 Really nice.
MartyIX
+1  A: 
void EncodeAndFormat(string format, params object[] args)
{
     return string.Format(format, 
             args.Select(obj=>HttpUtility.UrlEncode(obj.ToString()).ToArray());
}


EncodeAndFormat("{0}, {1}, {2}", var1, var2, var3) 
James Curran