Generic DataRow extension

喜你入骨 提交于 2019-12-10 21:12:26

问题


I use a extension method to check a DataRowField for null

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

Now I wonder if i could make this more generic. In my case the return type is always string but the Column could also be Int32 or DateTime

Something like

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

回答1:


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

or for earlier C# versions:

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;
}

and sample uses (the underlying type has to match exactly as there is no conversion):

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

Other alternatives without extension can be nullable types:

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

The column name lookup is slower if the case doesn't match, because a faster case sensitive lookup is attempted first before the slower case insensitive search.




回答2:


Signature of your method will be as follows

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

In Else part just change the following

return (T)Row[Column];


来源:https://stackoverflow.com/questions/39723298/generic-datarow-extension

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!