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:
Perfect,Thanks a lot!
This is exactly what I was looking for.
Posta un commento