我需要根据DataTable中DataColumns的类型格式化输出。
具体来说,我需要将内置的基本类型(int,string,decimal,DateTime等)映射到:
我怎么能这样做?
答案 0 :(得分:10)
如果内置的TypeCode
枚举符合您的需求,那么您只需阅读DataColumn
的{{3}}属性,然后拨打DataType
,
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;
}
如果TypeCode
无法满足您的需求,那么您只需将列类型转换为您自己的自定义枚举,如GetTypeCode
中所述。
答案 1 :(得分:1)
您可以使用:
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]);