0

I have two tables named table 1 and table 2: now i want to fill column which is in table 2 from column which is in table 1.

table 1

Date |  Value
-------------
5     |  678 
10    |  135  
15    |  420


table 2
Date  |  Value | Value2
------------------------
1     |  100   |
2     |  200   |
3     |  300   |
4     |  400   |
5     |  500   |  678
6     |  600   |
7     |  700   |
8     |  800   |
9     |  900   |
10    |  1000  |  135
11    |  1100  |
12    |  1200  |
13    |  1300  |
14    |  1400  |
15    |  1500  |  420
16    |  1600  |
17    |  1700  |

I am using below code for filling the datavalue using foreach loop. But It takes more time to evaluate.I want to do using Linq. Can anyone help me ?

foreach (DataRow row in table.Rows)
            {

                string date= Convert.ToString(row["date"]);
                if (!string.IsNullOrEmpty(date))
                {
                    foreach (DataRow sheetRow in table1.Rows)
                    {
                        if (sheetRow["Date"] != DBNull.Value)
                        {
                            // Assuming that given columns in both datatables are of same type
                            if (Convert.ToDateTime(date) == Convert.ToDateTime(sheetRow["Date"]))
                            {
                                row["Value"] = sheetRow["Value"];
                                break;
                            }
                        }
                    }
                }
                return table2;
  • Maybe help you http://stackoverflow.com/a/11593/316799 – Felipe Oriani Sep 30 '16 at 11:48
  • 1
    I know nothing about linq but what you want to do is a single SQL statement, so I would be really supprised if you needed any loops for linq. All you have to do is select the values from Table 1 and insert them into table 2 where the dates match. – Code Gorilla Sep 30 '16 at 12:06
  • " It takes more time to evaluate" - more time than what? Linq doesn't make looping _faster_ it makes it _easier to code_. It still uses loops behind-the-scenes. – D Stanley Sep 30 '16 at 13:44

1 Answers1

0

try this

   context.table2.Join(context.table1, t2 => t2.Date, t1 => t1.Date, (t2, t1) => t2.Value2 = t1.value);

let me know if this helps.

srini
  • 170
  • 4
  • Did you try what would be the result of this linq query, also does this query will do the assignment as suggested. Also why value is assigned to value2. To correct return t2 post assignment so the result is the final DataTable – Mrinal Kamboj Sep 30 '16 at 19:16