【问题标题】:Join the datatable using Linq使用 Linq 加入数据表
【发布时间】:2016-09-30 11:44:14
【问题描述】:

我有两个表,分别命名为表 1 和表 2: 现在我想从表 1 中的列中填充表 2 中的列。

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  |

我正在使用以下代码使用 foreach 循环填充数据值。 但评估需要更多时间。我想使用 Linq。谁能帮帮我?

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;

【问题讨论】:

  • 我对 linq 一无所知,但您想要做的是单个 SQL 语句,所以如果您需要任何用于 linq 的循环,我会非常惊讶。您所要做的就是从表 1 中选择值并将它们插入到日期匹配的表 2 中。
  • "评估需要更多时间" - 比什么时间更长? Linq 并没有使循环更快,它使它更容易编码。它仍然在幕后使用循环。

标签: c# .net linq datatable


【解决方案1】:

试试这个

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

如果这有帮助,请告诉我。

【讨论】:

  • 您是否尝试过此 linq 查询的结果,此查询是否会按照建议进行分配。还有为什么将 value 分配给 value2。更正返回 t2 后分配,因此结果是最终的 DataTable
猜你喜欢
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多