循环遍历数据表以获取值 [英] Looping through data table to get value
问题描述
我有一个包含多行的数据表.我正在使用 foreach 循环来遍历每个项目并返回名称.这将为每一行返回相同的(第一个)值.我做错了什么?
I have a DataTable with multiple rows. I'm using a foreach loop to loop through each item and return the name. This is returning the same (1st) value for each row. What have I done wrong?
DataTable table = new DataTable();
table.Columns.Add("tag", typeof(string));
string name = hfSelected.Value;
string[] names = name.Split(',');
for (int i = 0; i < names.Length; i++)
table.Rows.Add(new object[] { names[i] });
DataRow row = table.Rows[0];
foreach (var item in table.Rows)
{
Value = row["tag"].ToString() // this is returning the same value for both items in the table.
}
推荐答案
在您提到您收到错误的评论中:
In a comment you mentioned that you get the error:
不能将带有 [] 的索引应用于对象类型的表达式
cannot apply indexing with [] to an expression of type object
在 foreach 循环中尝试访问 item["tag"]
时.
when trying to access item["tag"]
in the foreach loop.
您需要在 foreach 中显式声明 DataRow
.
You need to explicitly declare the DataRow
in the foreach.
// declare DataRow here, not var
foreach (DataRow item in table.Rows)
{
// use item here
Value = item["tag"].ToString(); // use += to concatenate string
}
原因是 DataRowCollection
实现了一个非通用的 IEnumerable
所以你索引一个 object
而不是 DataRow
.上面的解决方案转换为 DataRow
.
The reason is that the DataRowCollection
implements a non-generic IEnumerable
so you index an object
instead of DataRow
. The solution above casts to a DataRow
.
我建议查看 System.Data.DataSetExtensions
中的 Field
和 AsEnumerable()
方法.AsEnumerable() 返回 IEnumerable
.Field() 提供对值的强类型访问(即它为您强制转换/转换类型).
I would recommend looking at the Field<T>()
and AsEnumerable()
methods from System.Data.DataSetExtensions
. AsEnumerable() returns an IEnumerable<DataRow>
. Field() provides strongly typed access to the values (ie it casts/converts the types for you).
然后你可以这样做:
foreach (var item in table.AsEnumerable())
{
// item is a DataRow here
var myString = item.Field<string>("tag"); // gets string
// you can also do
var myInt = item.Field<int>("Id"); // gets int
var myDate = item.Field<DateTime?>("Date"); // gets nullable DateTime?
var myValue = item.Field<decimal>("Price"); // gets decimal
}
这篇关于循环遍历数据表以获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!