Skatz1990 Skatz1990 - 1 year ago 94
C# Question

C# string format unkown size

Let's say I have the following string:

string postData = "state={2}&country={3}&geolocation={0}&city={1}";

And I have another list of strings. Its size could be in this case 4 at most.
I'm trying to create a method which replaces the numbers in my postData variable, depending on the list size. Something like the following method:

private string UnknownSizeStringFormat(string postData, params string[] stringsToReplace)
return string.format(postData, stringsToReplace);

The above method works as long as the list's size is 4. The thing is, on the first call, my list's size could be smaller than 4, so if it's 0 for example, I would like to replace each number inside the brackets with an empty string. My return value should be:


If its size is one, and the first member in the list is "21,27" my return string should be:


And so on...
I could use a loop or a Regular Expression for this purpose but I've been wondering if there is a better way, a Linq solution perhaps? What I do know is how many numbers postData could have at most, which in my case is 4.
Again, I could do that with a loop or a Regular Expression, but I'm trying to make it as short as possible

Edit: The postData string could vary. That was just an example. Its size or content could be different

Answer Source

What I do know is how many numbers postData could have at most

Then how about this:

static string UnknownSizeStringFormat(string format, int maxArgs, params object[] args)
    Array.Resize(ref args, maxArgs);
    return string.Format(format, args);

so you can use:

string postData = "state={2}&country={3}&geolocation={0}&city={1}";
var result = UnknownSizeStringFormat(postData, 4);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download