Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Applying same function to different variables

Tags:

c#

linq

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.

like image 954
halivingston Avatar asked Feb 26 '23 10:02

halivingston


1 Answers

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;
}
like image 168
dtb Avatar answered Mar 07 '23 10:03

dtb