18

DataTableのDataColumnが数値(SQL Serverデータベースからのもの)であるかどうかを確認するためのこれよりも優れた方法はありますか?

  Database db = DatabaseFactory.CreateDatabase();
  DbCommand cmd = db.GetStoredProcCommand("Get_Some_Data");
  DataSet ds = db.ExecuteDataSet(cmd);

  foreach (DataTable tbl in ds.Tables) {
    foreach (DataColumn col in tbl.Columns) {
      if (col.DataType == typeof(System.Single)
        || col.DataType == typeof(System.Double)
        || col.DataType == typeof(System.Decimal)
        || col.DataType == typeof(System.Byte)
        || col.DataType == typeof(System.Int16)
        || col.DataType == typeof(System.Int32)
        || col.DataType == typeof(System.Int64)) {
        // this column is numeric
      } else {
        // this column is not numeric
      }
    }
  }
4

3 に答える 3

42

実際の型と比較する以外に、型が数値かどうかを確認する良い方法はありません。これは、数値の定義が
少し異なる 場合に特に当てはまります (あなたの場合、コードによれば、符号なし整数は数値ではありません)。

もう 1 つのことは、MSDN によると DataColumn.DataTypeは次の型のみをサポートすることです。

  • ブール値
  • バイト
  • シャア
  • 日付時刻
  • 小数
  • ダブル
  • Int16
  • Int32
  • Int64
  • Sバイト
  • 独身
  • 期間
  • UInt16
  • UInt32
  • UInt64
  • バイト[]

太字のタイプは (私が定義するように) 数値であるため、必ず確認する必要があります。

個人的には、DataColumn 型の拡張メソッドを作成します (TYPE ではありません!)。
私はif...then..elseが嫌いなので、代わりに次のようにSETSベースのアプローチ を使用します。

public static bool IsNumeric(this DataColumn col) {
  if (col == null)
    return false;
  // Make this const
  var numericTypes = new [] { typeof(Byte), typeof(Decimal), typeof(Double),
        typeof(Int16), typeof(Int32), typeof(Int64), typeof(SByte),
        typeof(Single), typeof(UInt16), typeof(UInt32), typeof(UInt64)};
  return numericTypes.Contains(col.DataType);
}

使用法は次のようになります。

if (col.IsNumeric()) ....

これは私にとって十分に簡単です

于 2009-11-12T23:04:57.553 に答える
2

コードを 1 行だけ使用する、配列を使用しない別の方法:

return col != null && "Byte,Decimal,Double,Int16,Int32,Int64,SByte,Single,UInt16,UInt32,UInt64,".Contains(col.DataType.Name + ",");

このコード行は、通常のヘルパー メソッドまたは拡張メソッドとして使用できます。

于 2013-09-23T10:53:49.807 に答える
1

多分あなたはそれを短くすることができます:

System.Type theType = col.DataType AS System.Type
if(theType  == System.Single || theType  == System.Double...) {}
于 2009-11-12T22:51:30.710 に答える