如何将两个DataTable与常用值进行比较

时间:2016-04-12 10:39:06

标签: c# linq datatable

我有两个数据表dt1和st2。

dt1由PorductId ProductName FilePath组成:

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")

2 个答案:

答案 0 :(得分:1)

你真正要做的是先用第一个过滤第二个数据表,我会使用where而不是连接,下面的例子应该复制你想要做的事情:

//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();

希望有所帮助

答案 1 :(得分:0)

尝试测试此代码

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();