【问题标题】:How to compare two DataTables with common values如何比较两个具有共同值的数据表
【发布时间】:2016-08-02 22:05:44
【问题描述】:

我有两个数据表 dt1 和 st2。

dt1由PorductIdProductNameFilePath组成:

1   Product1   c:\
2   Product2   c:\
3   Product3   c:\
4   Product4   c:\

dt2 由ProductName DateofDelivery 组成:

Product2   2016-01-03
Product3   2016-03-02
Product5   2016-02-03
Product7   2014-09-01

我需要从 dt2 返回所有行,其中 dt2 的 ProductName 在 dt1 中,结果应该是:

Product2   2016-01-03
Product3   2016-03-02

我试过了,但它不起作用:

var matched = from table1 in dt1.AsEnumerable()
    join table2 in dt2.AsEnumerable() 
    on table1.Field<string>("ProductName") equals table2.Field<string>("ProductName")

【问题讨论】:

    标签: c# linq datatable


    【解决方案1】:

    尝试测试此代码

    var dtproducts = dt1.Rows.Select(x => [ProductName]).ToArray();
    
    var matches = (from System.Data.DataRow product in st1.Rows
                    where dtproducts.Contains(product["ProductName"])
                    select product).ToList();
    

    【讨论】:

      【解决方案2】:

      您真正想要做的是通过第一个过滤第二个 Datatable,我会使用 where 而不是 join,下面的示例应该复制您尝试做的事情:

      //Assemble the DataTables mentioned in your question
      DataTable dt1 = new DataTable();
      
      dt1.Columns.Add("ID", typeof(int));
      dt1.Columns.Add("ProductName", typeof(string));
      dt1.Columns.Add("Path", typeof(string));
      
      dt1.Rows.Add(1, "Product1", "c:\\");
      dt1.Rows.Add(2, "Product2", "c:\\");
      dt1.Rows.Add(3, "Product3", "c:\\");
      dt1.Rows.Add(4, "Product4", "c:\\");
      
      DataTable dt2 = new DataTable();
      dt2.Columns.Add("ProductName", typeof(string));
      dt2.Columns.Add("Date", typeof(string));
      
      dt2.Rows.Add("Product2", "2016-01-03");
      dt2.Rows.Add("Product3", "2016-01-04");
      dt2.Rows.Add("Product5", "2016-01-05");
      dt2.Rows.Add("Product7", "2016-01-06");
      
      //Get the values from dt1 to filter by
      var filter = dt1.AsEnumerable().Select(b => b.Field<string>("ProductName")).ToList();
      
      //Then filter the second list by the ProductName of the first list
      var matched = dt2.AsEnumerable().Where(a => filter.Contains(a.Field<string>("ProductName")))
      .ToList();
      

      希望有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-10
        • 1970-01-01
        • 2019-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多