[英]How to compare two DataTables with common values
我有兩個數據表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")
確實,您要執行的操作是按第一個過濾第二個數據表,我將使用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();
希望能有所幫助
嘗試測試此代碼
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.