Does Array.ToString() provide a useful output?

前端 未结 6 989
北海茫月
北海茫月 2020-12-03 13:31

If I have an array and perform a ToString() does that just string together the array values in one long comma seperated string or is that not possible on an arr

相关标签:
6条回答
  • 2020-12-03 13:48

    You can certainly do that, but it's not the default behaviour. The easiest way to do that (from .NET 3.5 anyway) is probably:

    string joined = string.Join(",", array.Select(x => x.ToString()).ToArray());
    

    MoreLINQ has a built-in method to do this:

    string joined = array.ToDelimitedString();
    

    or specify the delimited explicitly:

    string joined = array.ToDelimitedString(",");
    
    0 讨论(0)
  • 2020-12-03 13:51

    Option 1

    If you have an array of strings, then you can use String.Join:

    string[] values = ...;
    
    string concatenated = string.Join(",", values);
    

    Option 2

    If you're dealing with an array of any other type and you're using .NET 3.5 or above, you can use LINQ:

    string concatenated = string.Join(",",
                              values.Select(x => x.ToString()).ToArray());
    
    0 讨论(0)
  • 2020-12-03 13:55

    It doesn't (as you noticed).

    For string arrays you can use:

    string.Join(",", myArray)
    

    for other arrays I think you need to code it yourself.

    0 讨论(0)
  • 2020-12-03 13:57

    No, ToString of an array will give you the Type name string of the object. use String.Join method instead.

    0 讨论(0)
  • 2020-12-03 14:11

    To achieve this effect you should call String.Join(string, string[])

    I.e.

    string[] stringArray = new string[] { "a", "b", "c" };
    string.Join(",", stringArray);
    
    0 讨论(0)
  • 2020-12-03 14:12

    You can use string.Concat(Object[] args). This calls the ToString() method of every object in args. In a custom class you can override the ToString() method to achieve custom string conversion like this:

    public class YourClass
    {
        private int number;
    
        public YourClass(int num)
        {
            number = num;
        }
    
        public override string ToString()
        {
            return "#" + number;
        }
    }
    

    Now you can concatenate an array of instances of your custom class:

    YourClass[] yourArray = { new YourClass(1), new YourClass(2), new YourClass(3) };
    string concatenated = string.Concat(yourArray);
    

    Unfortunately this method does not add any delimiters, but I found it to be elegant. The variable concatenated will contain "#1#2#2".

    0 讨论(0)
提交回复
热议问题