martedì, gennaio 29, 2008

Convert int[] to string[]

It's very common to need to convert an array of type T1 to an array of type T2.
Net 2.0 offers an interesting static member of the Array class: ConvertAll.
Using anonymous methods (MSDN) in conjunction with ConvertAll, you can convert an array of "simple" type to an array of another "simple" type in only ONE line of code.

An example: int[] to string[]

int[] inInt = new int[] { 47, 46, 45, 101 };

string[] outStr = Array.ConvertAll<int, string>(inInt, new Converter<int, string>(delegate(int x) { return x.ToString(); }));


or (smaller):

string[] outStr = Array.ConvertAll<int, string>(inInt, delegate(int x) { return x.ToString(); });


You can also convert string[] to int[]:

int[] outInt2 = Array.ConvertAll<string, int>(outStr, delegate(string s) { return int.Parse(s); });



If you need to convert between more complex type, probably you need more code in the delegate body. But the idea is the same: use a delegate as a converter between 2 types.

1 commento:

Anonimo ha detto...

Perfect,Thanks a lot!
This is exactly what I was looking for.