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.
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())));
                        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();
}
                        I regularly use...
String.Join(", ", Array.ConvertAll<object, string>(myArray, Convert.ToString))
                        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);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With