从循环中联接数据表并合并到一个数据集中

本文关键字:一个 数据 集中 数据集 循环 数据表 合并 | 更新日期: 2023-09-27 18:00:49

我有一个要求,即用户请求一个或多个零件号。我需要在一个数据集中显示所有结果

例如:带有的请求序列号

PartNumber  Required Quantity
   A               2  
   B               1
   C               3

代码:

//环路请求

foreach (DataRow a in request.Rows)
{
   //select top(Quantity) SerialNumber,PartNumber where PartNumber=@PartNumber
   var dt = new DataTable();
} 

//1.零件号A

     SerialNumber  Partnumber
1                A
2                A

+

//2.零件号B

     SerialNumber  Partnumber
1                B

//3.零件号C

     SerialNumber  Partnumber
1                C
2                C
3                C

//加载到数据集

结果是:

SerialNumber  Partnumber
1                A
2                A
1                B   
1                C
2                C
3                C 

感谢

从循环中联接数据表并合并到一个数据集中

我不确定您希望在这里连接哪两个表以及在哪个键上连接,但不管怎样,最简单的方法是使用LINQ to Dataset。例如,

var query = from a in table1
            join
            b in table2 
            on
            a.FkColumn = b.PKColumn select a,b;

请检查以下逻辑:

DataTable myDataTable = new DataTable();
        DataColumn PartNumber = new DataColumn("PartNumber");
        DataColumn RequiredQuantity = new DataColumn("RequiredQuantity");
        myDataTable.Columns.Add(PartNumber);
        myDataTable.Columns.Add(RequiredQuantity);
        DataRow dataRowPN1 = myDataTable.NewRow();
        DataRow dataRowPN2 = myDataTable.NewRow();
        DataRow dataRowPN3 = myDataTable.NewRow();

        dataRowPN1["PartNumber"] = "A";
        dataRowPN2["PartNumber"] = "B";
        dataRowPN3["PartNumber"] = "C";
        dataRowPN1["RequiredQuantity"] = "2";
        dataRowPN2["RequiredQuantity"] = "1";
        dataRowPN3["RequiredQuantity"] = "3";
        myDataTable.Rows.Add(dataRowPN1);
        myDataTable.Rows.Add(dataRowPN2);
        myDataTable.Rows.Add(dataRowPN3);
        int  i = myDataTable.Rows.Count;
        DataTable joinDataTable = new DataTable();
        DataColumn SerialNumber = new DataColumn("SerialNumber");
        DataColumn JoinPartNumber = new DataColumn("PartNumber");
        joinDataTable.Columns.Add(SerialNumber);
        joinDataTable.Columns.Add(JoinPartNumber);
        foreach (DataRow dr in myDataTable.Rows)
        {
            for (int count = 1; count <= Convert.ToInt16(dr["RequiredQuantity"]); count++)
            {
                DataRow joindataRow = joinDataTable.NewRow();
                joindataRow["SerialNumber"] = count.ToString().Trim();
                joindataRow["PartNumber"] = dr["PartNumber"].ToString().Trim();
                joinDataTable.Rows.Add(joindataRow);
            }
        }
        Response.Write(joinDataTable.Rows.Count);