简体   繁体   中英

Join the datatable using Linq

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM