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

时间:2010-11-29 08:35:52

标签: c# .net datatable datarow

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

3 个答案:

答案 0 :(得分: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();
 }

答案 1 :(得分:5)

DataTable tbl = new DataTable();
foreach (DataRow row in tbl.Rows)
{
    object cellData = row["colName"];
}

答案 2 :(得分:5)

您可以尝试下面的代码段

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1 { class Program { public static DataTable GetDataTable() { //Create a new DataTable object DataTable objDataTable = new DataTable(); //Create three columns with string as their type objDataTable.Columns.Add("Column 1", typeof(string)); objDataTable.Columns.Add("Column 2", typeof(string)); objDataTable.Columns.Add("Column 3", typeof(string)); //Adding some data in the rows of this 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); } } }

}