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

By Akbar


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

Tags: , , ,