0

i am looping through a dataset with 2 loops trying to find the rows which have have their ID matched with the assigned value to an array and if they matched i would like to copy that row into another table. for example:

DataSet dsWinners = new DataSet();
for(int i =0;i<=TotalWinners;i++)
{
    for (int j = 1; j <= ds.Tables[0].Rows.Count; j++)
    {
        //this is my ds table 0
        left = Convert.ToInt16(ds.Tables[0].Rows[i]["ID"]);
        //this is my array 
        right = Convert.ToInt16(Winners[i, 0]);

        if ( left == right )//if array value matechs with ds.table[0] ID
        {
            dsWinners.Tables[0].Rows[i] = ds.Tables[0].Rows[j];
        }
    }
}

how can i get record/row And copy it into a new table and if i cant copy that row like this, is there an alternative way to do it?

Ali
  • 2,331
  • 3
  • 24
  • 37

4 Answers4

2
    DataTable tempDt = new DataTable();
    tempDt = ds.Tables[0].Clone();
    ds.Tables[0].Rows.OfType<DataRow>().ToList().ForEach(x =>
    {
        int rowIndex = ds.Tables[0].Rows.IndexOf(x);
        if (rowIndex < TotalWinners && 
            Convert.ToInt16(x["ID"]) == Convert.ToInt16(Winners[rowIndex, 0]))
        {
            tempDt.ImportRow(x);
        }
    });
    DataSet dsWinners = new DataSet();
    dsWinners.Tables.Add(tempDt);

EDIT:

    Dictionary<string, string> winnersList = new Dictionary<string, string>();
    for (int i = 0; i < TotalWinners; i++)
    {
        winnersList.Add(Winners[i, 0], Winners[i, 1]);
    }
    string idList = string.Join("','", winnersList.Select(x => x.Key));
    DataSet dsWinners = new DataSet();
    dsWinners.Tables.Add(ds.Tables[0].Select("ID IN ('" + idList + "')").CopyToDataTable());
    dsWinners.Tables[0].Columns.Add("prize_amt", typeof(string));
    dsWinners.Tables[0].Rows.OfType<DataRow>().ToList().ForEach(x =>
    {
        x["prize_amt"] = winnersList[x["ID"].ToString()];
    });
    dsWinners.Tables[0].AcceptChanges();

Hope this helps...

Vanest
  • 888
  • 5
  • 13
  • @Ali How about this? – Vanest Jun 09 '15 at 05:36
  • i get "Index was outside the bounds of the array." on if line !!! – Ali Jun 09 '15 at 05:42
  • @Ali How about this edited one? Now its assumed that `TotalWinners` is the number of elements in your array – Vanest Jun 09 '15 at 05:54
  • its working but the result im getting is wrong. im only getting 1 row ! – Ali Jun 09 '15 at 05:59
  • and sometimes i get none actually! – Ali Jun 09 '15 at 06:21
  • 1
    @Ali Could you please try my edited answer... – Vanest Jun 09 '15 at 06:23
  • its getting result but the result are not the ones coming from the array!!! – Ali Jun 09 '15 at 06:29
  • What is the type of `ID` field in `ds.Tables[0]` table? – Vanest Jun 09 '15 at 06:35
  • its string but i convert it to int everytime. i had to get it string bcoz the array is a 2D array. the first part is a random ID and the second part is the category which is string. – Ali Jun 09 '15 at 06:39
  • oh i just found that i actually gives the right result ...just that it gives it in a random sort. THANK YOU VERY MUCH – Ali Jun 09 '15 at 06:43
  • just a quick question if you dont mind me asking, if i want to add the second part of the array to dsWinners, how would i be able to do that? – Ali Jun 09 '15 at 06:48
  • Second part of the 2D array is a string field right? and also what is the name of the corresponding field in `ds.Tables[0]`? – Vanest Jun 09 '15 at 06:52
  • that is not included in the ds! all of the numbers in first part of the array were random numbers, and second part is the prize they won. so i just want to add that to the table as well – Ali Jun 09 '15 at 06:53
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/80018/discussion-between-ali-and-vanest). – Ali Jun 09 '15 at 06:59
0
DataSet dsWinners = new DataSet();
DataTable dataTable= ds.Tables[0].Clone();

for(int i =0;i<=TotalWinners;i++)
  {
       for (int j = 1; j <= ds.Tables[0].Rows.Count; j++)
       {
          //this is my ds table 0
          left = Convert.ToInt16(ds.Tables[0].Rows[i]["ID"]);
          //this is my array 
          right = Convert.ToInt16(Winners[i, 0]);

          if ( left == right )//if array value matechs with ds.table[0] ID
          {
            //  dsWinners.Tables[0].Rows[i] = ds.Tables[0].Rows[j];
              dataTable.Rows.Add( ds.Tables[0].Rows[j]);
           }
      }
  }
dsWinners.Add(dataTable);
Kajal
  • 724
  • 6
  • 25
  • after solving that i get the following error :This row already belongs to another table. – Ali Jun 09 '15 at 05:55
  • change the last line to dsWinners.Tables.Add(dataTable); – Kajal Jun 09 '15 at 06:03
  • dataTable.Rows.Add( ds.Tables[0].Rows[j].ItemArray); // it will fix your problem, [link] (http://stackoverflow.com/questions/4020270/copy-rows-from-datatable-to-another-datatable-c-sharp) – Kajal Jun 09 '15 at 06:07
0
DataSet ds = new DataSet();

DataTable dt = new DataTable("ExampleTable");
dt.Columns.Add(new DataColumn("Age",typeof(int)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));

DataRow dr = dt.NewRow();
dr["Age"] = 30;
dr["Name"] = "Mike";
dt.Rows.Add(dr);
ds.Tables.Add(dt);
Olaru Mircea
  • 2,510
  • 24
  • 45
0

If i read your question right then you need to copy rows from one dataset when certain condition is met and transfer it to other one.Assuming that both the dataset have same structure this example should suffice.

      DataSet DSResult = new DataSet();
        DSResult.Tables.Add();

        DSResult.Tables[0].Columns.Add("ID", typeof(int));
        DSResult.Tables[0].Columns.Add("Name", typeof(string));

        DSResult.Tables[0].Rows.Add(1,"Jon");
        DSResult.Tables[0].Rows.Add(2, "Kyle");
        DSResult.Tables[0].Rows.Add(3, "Sam");
        DSResult.Tables[0].Rows.Add(4, "Peter");
        DSResult.Tables[0].Rows.Add(5, "Lily");


        DataSet DSWinners = new DataSet();
        DSWinners.Tables.Add();
        DSWinners = DSResult.Clone();

        int[] Id = new int[] { 1, 4, 5 }; //condition to match

        foreach (int val in Id)
        {
            DataRow[] Samplerow =
              DSResult.Tables[0].AsEnumerable()
             .Select((row, index) => new { row, index })
             .Where(item => item.row.Field<int>("ID") == val)
             .Select(item => item.row)
             .ToArray();
                DSWinners.Tables[0].ImportRow(Samplerow[0]);

            // If both tables are not same then
               string YourVal=Samplerow[0]["ID"].ToString();
                DSWinners.Tables[0].Rows.Add();
                DSWinners.Tables[0].Rows[0]["YourColumnname"]=Yourval //Should have same Datataype


        }
Rohit
  • 9,792
  • 7
  • 45
  • 81
  • you got me right. but there is a problem. both dataset dont have the same structure since one the data is filled in with all data and the second one is a new dataset – Ali Jun 09 '15 at 05:27
  • my datacolumn varies each time ... i cant add them manually – Ali Jun 09 '15 at 05:52