如何循环数据表中特定列的值?

我想循环遍历datatable中特定列的值? 任何人都可以请给C#编码?

您好,尝试下面的代码片段

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

命名空间ConsoleApplication1
{
课程
{
public static DataTable GetDataTable()
{
//创建一个新的DataTable对象
DataTable objDataTable = new DataTable();
//创建三列,其中包含字符串作为其类型
objDataTable.Columns.Add(“Column 1”,typeof(string));
objDataTable.Columns.Add(“Column 2”,typeof(string));
objDataTable.Columns.Add(“Column 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”});
return objDataTable;

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

}

尝试下面基于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(); } 
 DataTable tbl = new DataTable(); foreach (DataRow row in tbl.Rows) { object cellData = row["colName"]; }