Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

c# - difference between getting value from DataRow

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:

  • Is there a difference between using row["name"] and row.Field<string>("name")? Of course, the second way cast value to some type, but is there another difference?
  • Which method is better to use?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...