如何将两个DataTable与普通值进行比较 [英] How to compare two DataTables with common values

查看:191
本文介绍了如何将两个DataTable与普通值进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个datatable dt1和st2。

I have two datatable dt1 and 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的所有行,应该是:

I need to return all rows from dt2 where the ProductName of dt2 is in dt1 the result should be:

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

我已经尝试过这个,但它不工作:

I've tried this, but its not working:

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


推荐答案

是第一个过滤第二个Datatable,我会使用一个而不是一个连接,下面的示例应该复制你想要做的:

Really what you want to do is filter the second Datatable by the first, I would use a where instead of a join, the example below should replicate what your trying to do:

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

希望有帮助

这篇关于如何将两个DataTable与普通值进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆