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

ToInteger

Convert datatable field to int32

Source

/// <summary>
/// Convierte de Double a Int 
/// </summary>
/// <param name="file">Datarow</param>
/// <param name="columna">Index de la columna</param>
/// <param name="tipo"></param>
/// <returns></returns>
public static Int32 ToInteger(this DataRow file,int columna)
{

    try
    {
        if (file.ItemArray[columna].GetType().Name == "Decimal")
        {
            return Convert.ToInt32(file.Field<Decimal>(columna));
        }
        if (file.ItemArray[columna].GetType().Name == "String")
        {
            return Convert.ToInt32(file.Field<String>(columna));
        }
        if (file.ItemArray[columna].GetType().Name == "Double")
        {
            return Convert.ToInt32(file.Field<Double>(columna));
        }
        if (file.ItemArray[columna].GetType().Name == "Float")
        {
            return Convert.ToInt32(file.Field<float>(columna));
        }
        else
        {
            return Convert.ToInt32(file.Field<Object>(columna));
        }
    }

    catch (InvalidCastException ecast)
    { throw ecast; }
    catch (IndexOutOfRangeException iore)
    { throw iore; }
    catch (NullReferenceException f)
    { throw f; }
}

Example

var query1 = dtModel.AsEnumerable().Select(d => new
{                    
    iserie =  d.Field<String>(0),
    iBegin= d.ToInteger(1),
    iNow = d.ToInteger(2),
    iLess =d.ToInteger(3)                   

});

Author: David Silva ( invalidtruck)

Submitted on: 25 okt. 2012

Language: C#

Type: System.Int32

Views: 6710