如何使用C#在DataTable中“foreach”一列?
我如何foreach
每一列是一个数据行?
DataTable dtTable = new DataTable(); MySQLProcessor.DTTable(mysqlCommand, out dtTable); foreach (DataRow dtRow in dtTable.Rows) { //foreach(DataColumn dc in dtRow) }
这应该工作:
DataTable dtTable; MySQLProcessor.DTTable(mysqlCommand, out dtTable); // On all tables' rows foreach (DataRow dtRow in dtTable.Rows) { // On all tables' columns foreach(DataColumn dc in dtTable.Columns) { var field1 = dtRow[dc].ToString(); } }
我相信这是你想要的:
DataTable dtTable = new DataTable(); foreach (DataRow dtRow in dtTable.Rows) { foreach (DataColumn dc in dtRow.ItemArray) { } }
你可以这样做:
DataTable dt = new DataTable("MyTable"); foreach (DataRow row in dt.Rows) { foreach (DataColumn column in dt.Columns) { if (row[column] != null) // This will check the null values also (if you want to check). { // Do whatever you want. } } }
foreach(DataColumn column in dtTable.Columns) { }
像这样的东西:
DataTable dt = new DataTable(); // For each row, print the values of each column. foreach(DataRow row in dt .Rows) { foreach(DataColumn column in dt .Columns) { Console.WriteLine(row[column]); } }
http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx
在LINQ中,你可以做如下的事情:
foreach (var data in from DataRow row in dataTable.Rows from DataColumn col in dataTable.Columns where row[col] != null select row[col]) { // do something with data }
int countRow = dt.Rows.Count; int countCol = dt.Columns.Count; for (int iCol = 0; iCol < countCol; iCol++) { DataColumn col = dt.Columns[iCol]; for (int iRow = 0; iRow < countRow; iRow++) { object cell = dt.Rows[iRow].ItemArray[iCol]; } }