遍历数据表以获取价值 [英] Looping through data table to get value

查看:39
本文介绍了遍历数据表以获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多行的DataTable.我正在使用一个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:

无法将带有[]的索引应用于类型为object的表达式

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< T>() AsEnumerable()方法. AsEnumerable()返回 IEnumerable< DataRow> . 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).

然后您可以执行以下操作:

Then you can do:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆