使用列名从列中获取数据?

时间:2023-01-28 11:00:39

I iterate a DataTable's rows using -

我使用 - 迭代DataTable的行 -

DataTable dt = getDataTableFromSomeWhere();
DataRow row = null;
//for loop
row = dt.Rows[i];

How do I get the value of a column of the i-th row, by using the name of the column ? I can iterate the columns using dt.Columns[j], but thats not what I want.

如何使用列的名称获取第i行的列的值?我可以使用dt.Columns [j]迭代列,但这不是我想要的。

2 个解决方案

#1


3  

Just use the indexer taking a string parameter:

只需使用索引器获取字符串参数:

object value = row["ColumnName"];

EDIT: Assuming the value has been fetched in an appropriate type, I'd normally just cast to the CLR type you want:

编辑:假设已经以适当的类型获取值,我通常只是转换为您想要的CLR类型:

int someIntegerValue = (int) row["ColumnName"];

Sometimes you may need two levels of casting (one to unbox and then another to perform an actual value conversion) but it depends on what you need.

有时您可能需要两个级别的投射(一个用于拆箱,然后另一个用于执行实际值转换),但这取决于您的需求。

I would recommend against converting to a string representation and then parsing that, unless you've really got no alternative. Excessive string conversions not only harm performance (usually not relevant) but they lead to sloppy type choices.

我建议不要转换为字符串表示然后解析它,除非你真的没有其他选择。过多的字符串转换不仅会损害性能(通常不相关),而且会导致类型选择不稳定。

#2


0  

 string name = (string) row["ColumnName"];

or

要么

 int i = Convert.ToInt32( row["ColumnName"]);

referencing by name is tiny bit slower but way more readable.

按名称引用的速度稍微慢一些,但更具可读性。

#1


3  

Just use the indexer taking a string parameter:

只需使用索引器获取字符串参数:

object value = row["ColumnName"];

EDIT: Assuming the value has been fetched in an appropriate type, I'd normally just cast to the CLR type you want:

编辑:假设已经以适当的类型获取值,我通常只是转换为您想要的CLR类型:

int someIntegerValue = (int) row["ColumnName"];

Sometimes you may need two levels of casting (one to unbox and then another to perform an actual value conversion) but it depends on what you need.

有时您可能需要两个级别的投射(一个用于拆箱,然后另一个用于执行实际值转换),但这取决于您的需求。

I would recommend against converting to a string representation and then parsing that, unless you've really got no alternative. Excessive string conversions not only harm performance (usually not relevant) but they lead to sloppy type choices.

我建议不要转换为字符串表示然后解析它,除非你真的没有其他选择。过多的字符串转换不仅会损害性能(通常不相关),而且会导致类型选择不稳定。

#2


0  

 string name = (string) row["ColumnName"];

or

要么

 int i = Convert.ToInt32( row["ColumnName"]);

referencing by name is tiny bit slower but way more readable.

按名称引用的速度稍微慢一些,但更具可读性。