Tuesday 9 October 2007

Converting Arrays without for...loop construct

.NET has built-in functionality to convert one collection or array of one type (e.g. List<typename>) to another collection or array of another type. You don't need a for loop to do this at all. Here's how:

(from http://gsharper.blogspot.com/2007/04/convert-integer-array-to-string-array.html)

private void TestMethod(int[] intArray)
{
string[] stringArray = Array.ConvertAll (intArray,new Converter (ConvertIntToString)); string result = string.Join(",", stringArray);
}

private string ConvertIntToString(int intParameter)
{
return intParameter.ToString();
}

No comments: