tags:

views:

33

answers:

2

I need to format output according to the type of the DataColumns in a DataTable.

Specifically, I need to map the built-in primitive types (int, string, decimal, DateTime, etc) to:

  • SomeEnum.Numeric
  • SomeEnum.Bool
  • SomeEnum.DateTime
  • SomeEnum.String
  • SomeEnum.Unknown
  • SomeEnum.Null

How could I do this?

+1  A: 

You could use:

var types = new Dictionary<Type, SomeEnum>()
{
    { typeof(int), SomeEnum.Numeric },
    { typeof(long), SomeEnum.Numeric },
    { typeof(string), SomeEnum.String },
    ...
};

Func<Type, object, SomeEnum> getTypeEnum = (type, obj) =>
{
    var result = types.ContainsKey(type)
                     ? types[type]
                     : SomeEnum.Unknown;
    if (obj == null || obj is DBNull)
    {
        result = SomeEnum.Null;
    }

    return result;
};

...

var e = getTypeEnum(col.DataType, row[col]);
John Gietzen
This would be my solution too. There are only 17 [allowed types](http://msdn.microsoft.com/en-us/library/system.data.datacolumn.datatype.aspx).
Matthew Flaschen
I like the flourish of type inference, lambda, and object construction. :)
Jeff Meatball Yang
+1  A: 

If the built-in TypeCode enum meets your needs then you could just read the DataType property of your DataColumn and then call GetTypeCode,

TypeCode yourTypeCode = Type.GetTypeCode(yourDataColumn.DataType);

switch (yourTypeCode)
{
    case TypeCode.Byte:
    case TypeCode.SByte:
    case TypeCode.Int16
    case TypeCode.UInt16:
    case TypeCode.Int32:
    case TypeCode.UInt32:
    case TypeCode.Int64:
    case TypeCode.UInt64:
    case TypeCode.Single:
    case TypeCode.Double:
    case TypeCode.Decimal:
        Console.WriteLine("Numeric");
        break;
    case TypeCode.Boolean:
        Console.WriteLine("Bool");
        break;
    case TypeCode.DateTime:
        Console.WriteLine("DateTime");
        break;
    case TypeCode.String:
        Console.WriteLine("String");
        break;
    case TypeCode.Empty:
        Console.WriteLine("Null");
        break;
    default:    // TypeCode.DBNull, TypeCode.Char and TypeCode.Object
        Console.WriteLine("Unknown");
        break;
}

If TypeCode doesn't meet your needs then you could simply translate the column type into your own custom enum, as described in John's answer.

LukeH
I could return SomeEnum values instead of writing cout. Looks good.
Jeff Meatball Yang