Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# IEnumerable<Object> to string

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 image 708
Toto Avatar asked Sep 03 '09 09:09

Toto


4 Answers

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())));
like image 108
Guffa Avatar answered Sep 23 '22 14:09

Guffa


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();
}
like image 36
Jon Skeet Avatar answered Sep 22 '22 14:09

Jon Skeet


I regularly use...

String.Join(", ", Array.ConvertAll<object, string>(myArray, Convert.ToString))
like image 28
Richard Avatar answered Sep 26 '22 14:09

Richard


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);
like image 20
Martin Delille Avatar answered Sep 24 '22 14:09

Martin Delille