Akbar’s Weblog

November 6, 2007

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

Filed under: C# Tips — Tags: , , , — syedgakbar @ 2:12 am


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 );

5 Comments »

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

    Comment by Moe — April 25, 2008 @ 2:34 am

  2. 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()));

    Comment by Michael Brandt — November 3, 2008 @ 1:24 pm

  3. Very Cool! Thanks both of you!

    Comment by Mazhar Karimi — March 3, 2009 @ 1:08 pm

  4. Thank you A LOT.
    Delegates are nice!

    Comment by Bruno — August 19, 2009 @ 11:44 pm

  5. Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

    Comment by sandrar — September 10, 2009 @ 8:00 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.