2013-04-25 4 views
1

이 (불완전한) if 조건을 바꾸려면 간단한 조건이 필요합니다.열을 double로 변환 할 수 있는지 확인하는 방법은 무엇입니까? (DataTable.Column.DataType)

col.DataType.IsNumeric() 

을하지만, 그 클래스에 그런 방법은 없다 :

// i dont want to write all possible data types 
if (col.DataType == typeof(int) || col.DataType == typeof(int64) ... all types) 
{ 
    // i want to do something on numeric columns 
    // (convert all numbers to double datatype) 
} 
else 
{ 
    // string and other non-numbers will remain unchanged 
} 

나는 이런 식으로 뭔가를 시도하고 있었다.

데이터가 너무 많아 데이터에 TryParse() 메서드를 사용할 수 없습니다.

조건은 DataTable 열 데이터 형식 속성에서만 결정해야합니다.

if을 단순화하는 간단한 방법이 있습니까?

+0

가능한 반복되는 질문 : http://stackoverflow.com/questions/894263/how-to-identify-if-a-string-is- a-number – Javiere

+0

@Javiere 특정 데이터/변수가 숫자로 변환 가능한지 확인하고 싶지 않습니다. – Kamil

+0

에디션이 출시되기 전에 질문이 반복되었습니다. 이제는 유형이 숫자인지, 문제인지를 알아야한다는 것을 이해합니다. 이전에 해결 된 질문 : http://stackoverflow.com/questions/1749966/c-sharp-how-to-/13179018 # 13179018 – Javiere

답변

4

당신이했던 것처럼 데이터 유형을 사용하거나이 작업을 수행하는 함수를 만들 수 있습니다 (이 Determine if DataColumn is numeric 참조)

public static bool IsNumeric(this DataColumn col) { 

    if (col == null) 
    return false; 

    // all numeric types 
    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()) 
{ 
    // the column is numeric 
} 

를 사용 다음과 같이 메소드를 사용해보세요.

double temp; 
if (double.TryParse(col["Column"].ToString(), out temp)) 
{ 
    // the content can be converter and you can read it from temp variable. 
} 
+0

업데이트 된 질문 ("TryParse() 사용 안함 ...")을 참조하십시오. – Kamil

+0

그래서 전용 방법이 없으며 가능한 모든 유형의 목록이 필요합니다. 감사. – Kamil

+0

@ 카밀 난이 [링크] (http://stackoverflow.com/a/8836054/1993545) 더 읽기 쉬운 솔루션을 제공한다고 생각합니다 – WiiMaxx

1

DataColumn.DataType.Name 속성을 확인할 수도 있습니다. 같은 :

string[] IntType ={"Byte","Decimal","Double","Int16","Int32","SByte", 
       "Single","UInt16","UInt32","UInt64"}; 

static void Main(string[] args) 
{ 
    DataTable dt = new DataTable(); 
    dt.Columns.Add("num", typeof(int)); 
    dt.Columns.Add("str", typeof(string)); 
    Program p=new Program(); 
    string type = dt.Columns["num"].DataType.Name; 
    if (p.IntType.Contains(type)) 
    { 
     //True 
    } 

} 
0

이 작업을 시도 할 수 있습니다 :

if(Microsoft.VisualBasic.Information.IsNumeric 
    (
    Activator.CreateInstance(col.DataType 
    ) 
    ) 
관련 문제