C# 怎样在for循环中去除DataTable特定的项???
有两个DataTable,假设为DT1和DT2,在DT1中“编号”列有三个1,三个2,三个3我想通过它的编号,把编号相同的假设所有编号为2的行取出来给DT2,于是我用了一个for循环将DT1进行删除所有不等于2的行删除掉,剩下的则为编号为2的,可是出错了,代码如下:
DataTable DT1 = new DataTable(); DT1.Columns.Add("编号",typeof(int));DT1.Columns.Add("内容",typeof(string));DataRow rw1 = DT1.NewRow();rw1[0] = 1;rw1[1] = "北京";DT1.Rows.Add(rw1);DataRow rw2 = DT1.NewRow();rw2[0] = 1;rw2[1] = "上海";DT1.Rows.Add(rw2);DataRow rw3 = DT1.NewRow();rw3[0] = 1;rw3[1] = "天津";DT1.Rows.Add(rw3);DataRow rw4 = DT1.NewRow();rw4[0] = 2;rw4[1] = "武汉";DT4.Rows.Add(rw4);DataRow rw5 = DT1.NewRow();rw5[0] = 2;rw5[1] = "广州";DT1.Rows.Add(rw5);DataRow rw6 = DT1.NewRow();rw6[0] = 2;rw6[1] = "深圳";DT1.Rows.Add(rw6);DataRow rw7 = DT1.NewRow();rw7[0] = 3;rw7[1] = "重庆";DT1.Rows.Add(rw7);DataRow rw8 = DT1.NewRow();rw8[0] = 3;rw8[1] = "青岛";DT1.Rows.Add(rw8);DataRow rw9 = DT1.NewRow();rw9[0] = 3;rw9[1] = "沈阳";DT1.Rows.Add(rw9);for(int i=0;i<DT1.Rows.Count;i++){ if((int)DT1.Rows[i][0] != 2) { DT1.Rows[i].RemoveAt(i); }}DataTable DT2 = new DataTable();DT2 = DT1.Copy();