Sample code:
DataTable table = new DataTable();
// ...
// insert column to table
table.Columns.Add("name");
// ...
// insert value to table
foreach (DataRow row in table.Rows) {
row["name"];
row.Field<string>("name");
}
My question is:
row["name"]
and row.Field<string>("name")
? Of course, the second way cast value to some type, but is there another difference? A DataRow represent a row of data in data table. You add data to the data table using DataRow object. A DataRowCollection object represents a collection of data rows of a data table.
ColumnIndex - The index of the column whose value is to be retrieved from the DataRow.
A DataRow contains an individual row of data. The DataRow type provides ways to add, remove, or read cells from the enclosing data structure.
To create a new DataRow, use the NewRow method of the DataTable object. After creating a new DataRow, use the Add method to add the new DataRow to the DataRowCollection. Finally, call the AcceptChanges method of the DataTable object to confirm the addition.
See Remarks section, main differences described there:
The DataSet class represents null values with the Value instance of the DBNull class. A Language-Integrated Query (LINQ) expression that accessed a column with a null value would generate a InvalidCastException at run time. Additionally, DataSet does not support nullable types. The Field method provides support for accessing columns as nullable types. If the underlying value in the DataSet is Value, the returned nullable type will have a value of null.
If the value of the specified DataColumn is null and T is a reference type or nullable type, the return type will be null. The Field method will not return Value.
The Field method does not perform type conversions. If type conversion is required, you should first obtain the column value by using the Field method. The column value should then be converted to another type.
The last paragraph makes a point as I've often seen numbers stored as strings in database, therefore varchar
to int
conversion would be required on data retrieval, so in this case using DataColumn is better, e.g.:
int test = row.Field<int>("Test"); // InvalidCastException
int test = Convert.ToInt32(row["Test"]); // Works like a charm
DataRowExtensions.Field<T> Method (DataRow, String)
first appeared in .NET 3.5 and it "provides strongly-typed access to each of the column values in the specified row. The Field method also supports nullable types."
Afaik, row["name"]
returns object
, row.Field<string>("name")
returns a String
.
We shouldn't be comparing apples and pears, hence you should be asking what's better:
row["name"].ToString()
vs row.Field<string>("name")
and the answer is: they're same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With