ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ConvertTo<T>

Converts an Array of arbitrary type to an array of type T. If a suitable converter cannot be found to do the conversion, a NotSupportedException is thrown.

Source

public static T[] 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;
}

Example

int[] ipParts = Request.UserHostAddress.Split('.').ConvertTo<int>();

Author: Brandon Siegel

Submitted on: 3 jun. 2008

Language: C#

Type: System.Array

Views: 8286