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!

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

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.