日期:2014-05-18  浏览次数:20950 次

数据库中数据提取不同值
sql = "SELECT id,no,partno,model FROM Master"
遍历JX_Product_Master的值如下:

no partno model

1 sa pro

2 ds pro

3 kk pro

4 ks pro1

5 kad pro1

求分组的方法。要求把上边的值分成pro pro1二组,高人指点
set = WebData1.dataSet(sql);
foreach (DataRow drow in set.Tables[0].Rows)
{
  //怎么判断字段model变化

}

------解决方案--------------------
我写了段代码不知道是不是楼主要的意思:
C# code

   private DataTable InitTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("no");
            dt.Columns.Add("partno");
            dt.Columns.Add("model");
            return dt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = this.InitTable();

            DataRow dr;

            dr = dt.NewRow();
            dr["no"] = "1";
            dr["partno"] = "1_1";
            dr["model"] = "pro";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["no"] = "2";
            dr["partno"] = "2_1";
            dr["model"] = "pro";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["no"] = "3";
            dr["partno"] = "3_1";
            dr["model"] = "pro1";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["no"] = "4";
            dr["partno"] = "4_1";
            dr["model"] = "pro1";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["no"] = "5";
            dr["partno"] = "5_1";
            dr["model"] = "pro2";
            dt.Rows.Add(dr);

            //实现分组

            IDictionary<string, DataTable> tables = new Dictionary<string, DataTable>();

            foreach (DataRow r in dt.Rows)
            {
                string model = r["model"].ToString();

                DataTable newTable;

                if (!tables.ContainsKey(model))
                {
                    newTable = this.InitTable();
                    tables.Add(model, newTable);
                }
                else
                {
                    newTable = tables[model];
                }

                DataRow newRow = newTable.NewRow();
                
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    newRow[j] = r[j];
                }

                newTable.Rows.Add(newRow);

            }

            foreach (KeyValuePair<string, DataTable> keyAndValue in tables)
            {
                MessageBox.Show("model=" + keyAndValue.Key + "的表数据行数为:" + keyAndValue.Value.Rows.Count.ToString());
            }

        }