Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Seperator Delimited ToString for Array, List, Dictionary, Generic IEnumerable

0.00/5 (No votes)
20 Sep 2008 1  
In C#, there is an easy way to do ToString with separator delimited for Array, List, Dictionary and Generic IEnumerables by utilizing extension method in .NET

Introduction

In C#, there is an easy way to do ToString with separator delimited for Array, List, Dictionary and Generic IEnumerables by utilizing extension method in .NET

Background 

Extension Method in .NET framework.

Using the code  

 Lets try a simple example without using String.Join directly.

int[] intArray = { 1, 2, 3 };
Console.WriteLine(intArray.ToString(","));
// output 1,2,3
List<string> list = new List<string>{"a","b","c"};
Console.WriteLine(intArray.ToString("|"));
// output a|b|c 		 


The extension method for achieving above.

        public static string ToString<T>(this IEnumerable<T> source, string separator)
        {
            // check null, note source can be passed in as null.
            if (source == null)
                throw new ArgumentException("Parameter source can not be null.");
            // check if the separator is valid
            if (string.IsNullOrEmpty(separator))
                throw new ArgumentException("Parameter separator can not be null or empty.");
            // constructs an array of string by calling ToString on each element.
            string[] array = (from s in source where s != null select s.ToString()).ToArray();
            // utilize the exsiting string.Join
            return string.Join(separator, array);
        }

If the code references this ExtensionMethod class, the intelliSense in visual studio would promot you the extended ToString(string seperator) method, see the picture below,


 

Here are different scenarios  including int array, generic collection with complex type and struct and generic dictionary with complex type as value.

        static void Main(string[] args)
        {
            // Array ToString "," seperated
            int[] intArray = { 1, 2, 3 };
            Console.WriteLine(intArray.ToString(","));
            // output: 1,2,3

            // ArrayList ToString ":" seperated
            ArrayList arrayList = new ArrayList() { 1, 2, 3 };
            Console.WriteLine(intArray.ToString(":"));
            // output 1:2:3

            // A class object List ToString " - " seperated
            List<Foo> foos = new List<Foo>() 
            { 
                new Foo() { Name = "foo1", Number = 1 },
                new Foo() { Name = "foo2", Number = 2 },
                new Foo() { Name = "foo3", Number = 3 },
            };
            Console.WriteLine(foos.ToString(" - "));
            // output 'foo1 1' - 'foo2 2' - 'foo3 3'

            // A struct List ToString "||" seperated
            List<StructFoo> sfoos = new List<StructFoo>() 
            { 
                new StructFoo() { Name = "sfoo1", Number = 1 },
                new StructFoo() { Name = "sfoo2", Number = 2 },
                new StructFoo() { Name = "sfoo3", Number = 3 },
            };
            Console.WriteLine(sfoos.ToString("||"));
            // output 'sfoo1 1'||'sfoo2 2'||'sfoo3 3'

            // A generic dictionary ToString "," seperated
            Dictionary<int, Foo> dictionary = new Dictionary<int, Foo>()
            {
              { 1, new Foo() { Name = "foo1", Number = 1 }},
              { 2, new Foo() { Name = "foo2", Number = 2 }},
              { 3, new Foo() { Name = "foo3", Number = 3 }},
            };            
            Console.WriteLine(dictionary.ToString(","));
            // output: [1, 'foo1 1'],[2, 'foo2 2'],[3, 'foo3 3']

            Console.ReadLine();
        }

        class Foo
        {
            public string Name { get; set; }
            public int Number { get; set; }
            public override string ToString()
            {
                return "'" + Name + " " + Number + "'";
            }
        }

        struct StructFoo
        {
            public string Name { get; set; }
            public int Number { get; set; }
            public override string ToString()
            {
                return "'" + Name + " " + Number + "'";
            }
        }

Points of Interest

.NET extension method can be applied to any customized or built in types to enhance the functionality that was not shipped originally. This simply speeds up the programming at code level.  Let me know if you have better ideas or bug fix.

History 

Tested with the sample code provided in the zip file. 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here