Reputation: 39027
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:
How could I do this?
Upvotes: 3
Views: 9655
Reputation: 49544
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]);
Upvotes: 1
Reputation: 269368
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.
Upvotes: 10