8

For logging purposes, I would like to call the .ToString() method of every object on an object[] array. How can I do this in the simplest way?

Say I have :

   myArray = new Object[]{"astring",1, Customer}

   Log(????);

How can I pass a string such as its value is equal to:

"astring".ToString()+1.ToString()+Customer.ToString()

Or better, with comma between each value.

2

4 Answers 4

25

Like this:

Log(String.Join(", ", myArray.Select(o => o.ToString()).ToArray()));

Update:

From framework 4 the Join method can also take an IEnumerable<string>, so you don't need the ToArray:

Log(String.Join(", ", myArray.Select(o => o.ToString())));
Sign up to request clarification or add additional context in comments.

9 Comments

@Jonathan: Correct. I always write it that way, so I don't know why I didn't this time...
Jonathan, more what? If you were meant to use String, why did C# ship with the aliases at all?
@troethom: The intention of the code is somewhat more clear if you use the alias string for the type, and the class String when you use static methods in the class.
What is more clear? I truly believe it is bad practice to not be consistent.
BTW I think string is the MS standard; that is what StyleCop enforces.
|
4

MoreLINQ has a ToDelimitedString method for precisely this purpose.

It uses a StringBuilder rather than using String.Join (from what I remember from previous questions, the efficiency of the two approaches depends heavily on what the input is) but it's simple enough. Here's the core code (there are a couple of wrappers to allow a default delimiter):

private static string ToDelimitedStringImpl<TSource>
    (IEnumerable<TSource> source, string delimiter)
{
    Debug.Assert(source != null);
    Debug.Assert(delimiter != null);

    var sb = new StringBuilder();

    foreach (var value in source)
    {
        if (sb.Length > 0) sb.Append(delimiter);
        sb.Append(value);
    }

    return sb.ToString();
}

2 Comments

No need to check sb.Length on each iteration. You can discard the 1st delimiter by returning sb.ToString(1, sb.Length-1) .
@gimel: It's slightly more complicated than that, to take account of long delimiters and empty sources. There are better ways though... I'm also not keen on the lack of braces here. Will fix when I get time :)
2

I regularly use...

String.Join(", ", Array.ConvertAll<object, string>(myArray, Convert.ToString))

Comments

1

A simple old fashion way :

string myString = "";
foreach(Object o in myArray)
    myString += o.ToString() + ", ";
// Remove the extra comma
if(myString.Length >=2)
    myString.Remove(myString.Length - 2);

Comments

Your Answer

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.