3
\$\begingroup\$

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!

\$\endgroup\$

3 Answers 3

13
\$\begingroup\$

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);
\$\endgroup\$
4
\$\begingroup\$

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));
\$\endgroup\$
3
  • \$\begingroup\$ what is o2s ? \$\endgroup\$ Nov 16, 2011 at 15:22
  • \$\begingroup\$ @JesseC.Slicer: It's the function Vinko declares in the second half of the question. \$\endgroup\$
    – Bobby
    Nov 16, 2011 at 16:04
  • \$\begingroup\$ Gotcha - for some reason my eyes didn't see that when I first read it. Thanks. \$\endgroup\$ Nov 16, 2011 at 16:29
1
\$\begingroup\$

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

\$\endgroup\$
3
  • 1
    \$\begingroup\$ This overload an addition on 4 and I'm targeting 3.5 \$\endgroup\$
    – Vinko Vrsalovic
    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
    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
    Dec 19, 2011 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.