Convert long array to string array using anonymous delegates in C#

By Akbar 1 min read 5 comments


I was looking today for a simple technique to get a list of long array values as a comma separate string (something similar to what JavaScript does with arrays). I didn’t find any method of the Array and List objects to return that comma separated string.

Just before I decided to implement it using the old fashioned technique of foreach loop, I looked at the existing methods of the Strings class and found an interesting related method called String.Join. This method can take a string array and a separator and then return that as a single string. Interesting, but now how do we convert the long array to a string array? Another loop would not be worth all my research, so I browsed more and found a simple way to convert any type of array to the target type. This in C# is even more simple due to the anonymous delegates. Here is a sample code whic do this job:

// First Convert the long array to string arrayString[] strArray = Array.ConvertAll<long, string>(lngArray, new Converter<long, string>(delegate(long lNum) {return lNum.ToString();}));

// Now use the String.Join to get a comma seperated list of the array’s items

string strArrayList = String.Join(“,”, strArray );

Feedback & Comments

5 Responses

  1. hi,

    First of all. Thanks very much for your useful post.

    I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.

    Please let me introduce you some info related to this post and I hope that it is useful for .Net community.

    There is a good C# resource site, Have alook

    http://www.csharptalk.com/2009/09/c-array.html
    http://www.csharptalk.com/2009/10/creating-arrays.html

    simi

  2. Bruno

    Thank you A LOT.
    Delegates are nice!

  3. Mazhar Karimi

    Very Cool! Thanks both of you!

  4. Michael Brandt

    You can simplify it even further by using lambda:

    long[] numbers = new long[] { 1, 2, 3};
    string s = String.Join(“,”, Array.ConvertAll(numbers, i => i.ToString()));

  5. Nice! THanks for sharing this code; I knew it could be done; just didn’t know the syntax to get it done…

Leave a Reply