create datatable based on condition - loop issue

Padmanabhan, Venkatesh 120 Reputation points
2023-04-17T15:19:04.26+00:00

Hi . I have 3 datatables. First datatable contains 4 columns. Second datatable contains 8 columns, which is got from a database. The third datatable has 12 columns, which has the same column name from first datatable and second datatable . First datatable does not have any duplicates, while second datatable can contain duplicate rows. The third datatable rows should be created based on matching condition of a Job id column which is there in first datatable and second datatable. I tried the below code, but the looping seems to be incorrect.

if (datatable2.Rows.Count != 0)   //  getting value from database. contains duplicates
            {
                for (int i = 0; i <= datatable2.Rows.Count - 1; i++)
                {
                    DataRow row = datatable2.Rows[i];
                    string col1Value = row["JOB_NAME"].ToString();
                    for (int j = 0; j <= datatable1.Rows.Count - 1; j++)   // prefilled no duplicates
                    {
                        DataRow row1 = datatable1.Rows[i];
                        if (col1Value.Equals(row1["JobName"]))
                        {
                            DataRow dr = dataResultFinal.NewRow();
                            dr[0] = col1Value;
                            dr["Application"] = row1["Application"];
                            dr["Region"] = row1["Region"];
                            dr["Frequency"] = row1["Frequency"];
                            dr["START_TIME"] = row["START_TIME"];
                            dr["START_DATE"] = row["START_DATE"];
                            dr["JSTATUS"] = row["JSTATUS"];
                            dr["MSGTEXT"] = row["MSGTEXT"];
                           
                            dataResultFinal.Rows.Add(dr);    // third datatable and can contain the duplicates and all rows 
                        }
                    }
                }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,403 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 113.2K Reputation points
    2023-04-17T16:25:03.65+00:00

    Try to use j instead of i: DataRow row1 = datatable1.Rows[j].