2

我想遍历数据表中特定列的值?谁能给 C# 编码?

4

3 回答 3

6
DataTable tbl = new DataTable();
foreach (DataRow row in tbl.Rows)
{
    object cellData = row["colName"];
}
于 2010-11-29T08:42:13.157 回答
5

尝试以下基于 Linq 的解决方案

var values = (from t in dt.AsEnumarable() // dt is your data table
             select t[ColumnName]).ToList().ForEach(your expression );


 or try normal way 

 foreach(DataRow drow in dt.Rows)
 {
      string value = drow[columnname].ToString();
 }
于 2010-11-29T08:40:31.877 回答
5

嗨试试下面的代码片段

    使用系统;
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;
使用 System.Data;

命名空间 ConsoleApplication1 { 课堂节目 { 公共静态数据表 GetDataTable() { //创建一个新的DataTable对象 数据表 objDataTable = new DataTable(); //创建三列,其类型为字符串 objDataTable.Columns.Add("第 1 列", typeof(string)); objDataTable.Columns.Add("第 2 列", typeof(string)); objDataTable.Columns.Add("第 3 列", typeof(string)); //在这个DataTable的行中添加一些数据 objDataTable.Rows.Add(new string[] { "Row1 - Column1", "Row1 - Column2", "Row1 - Column3" }); objDataTable.Rows.Add(new string[] { "Row2 - Column1", "Row2 - Column2", "Row2 - Column3" }); objDataTable.Rows.Add(new string[] { "Row3 - Column1", "Row3 - Column2", "Row3 - Column3" }); 返回对象数据表;

} static void Main(string[] args) { foreach (DataRow row in GetDataTable().Rows) { object cellData = row["Column 1"]; Console.WriteLine(cellData); } } }

}

于 2010-11-29T08:55:59.553 回答