Narmeen Shahid
Narmeen Shahid

Reputation: 15

compare two data set and update row if record found match

i have two data sets :

Data Set 1 : ds1

        **Year            Period          Allowed**
         2012               1 
         2013               2
         2014               3
         2015               5

Data Set 2 : ds2

       **Year            Period**     
         2012               1 
         2012               2
         2014               3
         2014               5   

Desired Data set :

         **Year            Period          Allowed**
         2012               1                0
         2013               2                1
         2014               3                0
         2015               5                1

i want to compare both data set rows (year and Period) one by one and if record found same then add value "0" of column(Allowed) of first data set (i.e ds1)

Note: year and period of first data set must be same with year and period of second data set

Here is my code:

 for (int ds = 0; ds < ds1.Tables[0].Rows.Count; ds++)
       {            
         string year = ds1.Tables[0].Rows[ds]["YEAR"].ToString();
         string per = ds1.Tables[0].Rows[ds]["PER"].ToString();

 for (int count = 0; count < ds2.Tables[0].Rows.Count; count++)
        {
      string year1 = dsAllwedUser.Tables[0].Rows[count]["YEAR"].ToString();
      string per1 = dsAllwedUser.Tables[0].Rows[count]["PER"].ToString();
          if (year == year1 && per == per1)
                  {
                     row["Allowed"] = "0";
                     ds1.Tables[0].AcceptChanges();
                      row.SetModified();
                  }
            else
                {
                    row["Allowed"] = "1";
                    ds1.Tables[0].AcceptChanges();
                    row.SetModified();
                        }
                    }
                }

Correct me if i am wrong ...thanks in advance!!

Upvotes: 0

Views: 392

Answers (1)

Usama Ahmed
Usama Ahmed

Reputation: 26

The good way for compare a dataset with another dataset is to use DataTable.Select().

private static DataSet GetAllowdDataSet(DataSet ds1, DataSet ds2)
{
    DataSet ds = new DataSet();
    ds.Tables.Add(new DataTable());
    ds.Tables[0].Columns.Add("YEAR");
    ds.Tables[0].Columns.Add("PER");
    ds.Tables[0].Columns.Add("ALLOWED");
    DataRow[] dr = null;
    for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
    {
        string year = Convert.ToString(ds1.Tables[0].Rows[i]["YEAR"]);
        string per = Convert.ToString(ds1.Tables[0].Rows[i]["PER"]);
        dr = ds2.Tables[0].Select(string.Format(" YEAR = '{0}' AND PER = '{1}'", year, per));
        if (dr.Count() > 0)
        {
            ds.Tables[0].Rows.Add(new String[] { year, per, "0" });
        }
        else
        {
            ds.Tables[0].Rows.Add(new String[] { year, per, "1" });
        }
    }

    return ds;
}

Upvotes: 1

Related Questions