I have something akin to
object[] values = getValues();
string renderedValues = string.Join("-",
Array.ConvertAll<object,string>(values,
new Converter<object,string>(o2s)
));
where o2s
is
public static string o2s(object o) { return o.ToString(); }
Comments welcome!
3 Answers 3
There exists a method for that conversion already:
string renderedValues = string.Join(
"-",
Array.ConvertAll<object, string>(values, Convert.ToString)
);
Update:
In framework 4 an overload that takes an object array was added, so it will do the conversion for you:
string renderedValues = string.Join("-", values);
No need to create a new Converter
. Also, I'd rename the variable:
object[] values = getValues();
string joinedValues = string.Join("-", Array.ConvertAll<object,string>(values, o2s));
-
\$\begingroup\$ what is
o2s
? \$\endgroup\$Jesse C. Slicer– Jesse C. Slicer2011年11月16日 15:22:39 +00:00Commented Nov 16, 2011 at 15:22 -
\$\begingroup\$ @JesseC.Slicer: It's the function Vinko declares in the second half of the question. \$\endgroup\$Bobby– Bobby2011年11月16日 16:04:21 +00:00Commented Nov 16, 2011 at 16:04
-
\$\begingroup\$ Gotcha - for some reason my eyes didn't see that when I first read it. Thanks. \$\endgroup\$Jesse C. Slicer– Jesse C. Slicer2011年11月16日 16:29:43 +00:00Commented Nov 16, 2011 at 16:29
Why not (削除) Zoidberg (削除ここまで) simply this?
string renderedValues = string.Join("-", getValues());
Simply using the Join(string separator, params Object[] values)
overload: http://msdn.microsoft.com/en-us/library/dd988350.aspx
-
1\$\begingroup\$ This overload an addition on 4 and I'm targeting 3.5 \$\endgroup\$Vinko Vrsalovic– Vinko Vrsalovic2011年11月16日 10:51:48 +00:00Commented Nov 16, 2011 at 10:51
-
\$\begingroup\$ Any idea how the two patterns compare from a performance standpoint. (Just assume .NET 4 was an option) \$\endgroup\$JoeGeeky– JoeGeeky2011年12月17日 10:16:40 +00:00Commented Dec 17, 2011 at 10:16
-
\$\begingroup\$ No idea whatsoever. Do you see any reason to spend time making code more complicated and less straightforward than it needs to be? \$\endgroup\$ANeves– ANeves2011年12月19日 10:11:13 +00:00Commented Dec 19, 2011 at 10:11