Mega Code Archive

 
Categories / C# / Collections Data Structure
 

Convert array content to generic type array

//The MIT License (MIT) //http://arolibraries.codeplex.com/license using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; namespace AroLibraries.ExtensionMethods.Enumerable {     public static class ArrayExt     {         public static T[] Ext_ConvertTo<T>(this Array ar)         {             T[] ret = new T[ar.Length];             System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));             if (tc.CanConvertFrom(ar.GetValue(0).GetType()))             {                 for (int i = 0; i < ar.Length; i++)                 {                     ret[i] = (T)tc.ConvertFrom(ar.GetValue(i));                 }             }             else             {                 tc = System.ComponentModel.TypeDescriptor.GetConverter(ar.GetValue(0).GetType());                 if (tc.CanConvertTo(typeof(T)))                 {                     for (int i = 0; i < ar.Length; i++)                     {                         ret[i] = (T)tc.ConvertTo(ar.GetValue(i), typeof(T));                     }                 }                 else                 {                     throw new NotSupportedException();                 }             }             return ret;         }     } }