What is the recommended way to start using types from the returned DataRow in C #?

When navigating through a DataRow and encountered types such as

DataRow dr;
dr["someString"]
dr["someInteger"]
dr["somedata"]

What is the best way to get them into the appropriate data types? dr ["foo"] is just a common object.

Also, can they be easily converted to types with zero value? dr ["someInteger"] may be null.

+1
source share
5 answers

When reading from a DataRow, your biggest enemy is a null value. In a DataRow, when the value is null, it is not null: it is equal DBNull.Value.

if(DBNull.Value == null)
{
   // Will never happen
}

, , . , , DBNull:

string name = (string)dr["Name"];

LINQ, System.Data.DataSetExtensions System.Data

string name = dr.Field<string>("Name");

LINQ,

string name = null;
if(!dr.IsNull("Name"))
    name = (string)dr["Name"];

Field :

public static T GetValue<T>(object value)
{
    if (value == null || value == DBNull.Value)
        return default(T);
    else
        return (T)value;
}

:

string name = GetValue<string>(dr["Name"]);
+8

.net 3.5, , , :

 string somestring= row.Field<string>("SomeString");

, .

+3

:

(string) dr["someString"];
(int?) dr["someInteger"];
(byte[]) dr["somedata"];
+2
string GetString(DataRow dr, string ColumnName)
{
    if (dr.IsNull(ColumnName)) 
    {
        return null;
    }
    return (string)dr[ColumnName];
}
0
source

Another option is to use "how to"

string str = dr["someString"] as string;

if it is DBNull.Value (or any other object is not a type string), then str will get a real "zero". Otherwise, it will get the correct string value.

For value types, you can use a NULL value, i.e.

int? i = dr["someint"] as int?;

Again, it will get a real “zero” instead of DBNull.Value. However, with null types, you must remember that you are using .Value, i.e.

int x = i.Value + 5;
0
source

Source: https://habr.com/ru/post/1718860/


All Articles