C # Applying the same function to different variables

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

I want to apply URL encoding for each of var1, var2 and var3. It is not an array, so I cannot use Linq Aggregate for this.

Any ideas?

I would really like to place brackets around each variable.

+4
source share
2 answers

If you donโ€™t want to place UrlEncode(...) around each argument or define a helper function, the only way is to explicitly implicitly create the array 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 a comma between the elements:

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

Using 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; } 
+7
source
 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) 
+1
source

All Articles