2016-09-27 47 views
3

我使用扩展方法来检查DataRowField为空通用的DataRow扩展

public static string GetValue(this System.Data.DataRow Row, string Column) 
{ 
    if (Row[Column] == DBNull.Value) 
    { 
     return null; 
    } 
    else 
    { 
     return Row[Column].ToString(); 
    } 
} 

现在我不知道如果我能做出这样更通用。在我的情况下,返回类型始终是字符串,但列也可以的Int32或日期时间

喜欢的东西

public static T GetValue<T>(this System.Data.DataRow Row, string Column, type Type) 
+3

为什么你想返回字符串,如果它是一个int或日期时间?使用['DataRowExtensions.Field'-method](https://msdn.microsoft.com/en-us/library/system.data.datarowextensions.field(v = vs.110).aspx),这是强类型的甚至支持可空类型。 –

+0

返回一个'对象'而不是字符串。还要更改以下内容:if((object)Row [Column] == DBNull.Value)。然后,您不必将单元格值转换为字符串。 – jdweng

回答

5
public static T value<T>(this DataRow row, string columnName, T defaultValue = default(T)) 
    => row[columnName] is T t ? t : defaultValue; 

或更早C#版本:

public static T value<T>(this DataRow row, string columnName, T defaultValue = default(T)) 
{ 
    object o = row[columnName]; 
    if (o is T) return (T)o; 
    return defaultValue; 
} 

和样品用途(底层类型必须完全匹配,因为没有转换):

int i0 = dr.value<int>("col");  // i0 = 0 if the underlying type is not int 

int i1 = dr.value("col", -1);  // i1 = -1 if the underlying type is not int 

没有扩展其它替代方案可空类型:

string s = dr["col"] as string;  // s = null if the underlying type is not string 

int? i = dr["col"] as int?;   // i = null if the underlying type is not int 

int i1 = dr["col"] as int? ?? -1; // i = -1 if the underlying type is not int 

列名查找速度较慢,如果情况不匹配,because a faster case sensitive lookup is attempted first before the slower case insensitive search

+0

伟大的答案,谢谢 – Toshi

+0

如果需要更强大的方法,可以使用'Convert.ChangeType'来代替转换。 –

0

签名的方法将作如下

public static T GetValue<T>(this System.Data.DataRow Row, string Column) 

中的其他部分只是改变了以下

return (T)Row[Column];