Reputation: 15219
Having the exhaustive list of the string.Format
definitions as
public static String Format(IFormatProvider provider,String format, params object[] args);
public static String Format(String format, params object[] args);
public static String Format(String format, object arg0, object arg1, object arg2);
public static String Format(String format, object arg0);
public static String Format(String format, object arg0, object arg1);
and the following code
using System;
public class Program
{
public static void Main()
{
var myFormat = "(0:'{0}';1:'{1}')";
var myParams = new object[] {"arg1", "arg2"};
var myString = MyTest(myFormat, myParams);
Console.WriteLine(myString);
}
public static string MyTest(string format, params object[] args)
{
string myFirstArg = "arg0";
var result = string.Format(format, myFirstArg, args);
return result;
}
}
will give
(0:'arg0';1:'System.Object[]')
the question is now how to include the arg0
in myParams
, in order to have in output
(0:'arg0';1:'arg1';2:'arg2')
PS. (supposing myFormat = "(0:'{0}';1:'{1}';2:'{2}')";
)
Upvotes: 2
Views: 220
Reputation: 1802
I use Prepend extension method for such tasks:
class Program
{
static void Main()
{
string myFirstArg = "arg0";
var format = "(0:'{0}';1:'{1}';2:'{2}')";
var args = new object[] { "arg1", "arg2" };
var result = string.Format(format, args.Prepend(myFirstArg).ToArray());
}
}
public static class IEnumerableExtensions
{
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> collection, T element)
{
yield return element;
foreach (var e in collection) yield return e;
}
}
Upvotes: 0
Reputation: 3515
You could go with LINQ:
public static string MyTest(string format, params object[] args)
{
string myFirstArg = "arg0";
var result = String.Format(format, (new[] { myFirstArg }).Union(args).ToArray());
return result;
}
Upvotes: 2
Reputation: 310
You have to create another array with arg0 as first elem. Try this:
using System.Linq;
public static string MyTest(string format, params object[] args) {
var newarr = new object[] { "arg0" };
newarr.Concat(args);
var result = string.Format(format, newarr);
return result;
}
Upvotes: 1