简体   繁体   English

比较两个数据表以找到匹配的值

[英]Compare two datatables to find matching values

I have 2 data tables. 我有2个数据表。 Each one has one column and I want to compare them and get same values on them but it does not work. 每个人都有一列,我想对其进行比较并获得相同的值,但它不起作用。

This is my code: 这是我的代码:

string CurrentRequestUrl = (HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.ToString());
DataTable dt_Item = ERP.BLL_Menu_Item.Custom_Item_ID(CurrentRequestUrl);
DataTable dt2_SysRole = ERP.BLL_Sys_User_Role.Custom_Role(Convert.ToInt64(App.UserID));

var dtOne = (dt_Item.AsEnumerable()).ToList();
var dtTwo = (dt2_SysRole.AsEnumerable()).ToList();


IEnumerable<DataRow> objIntersectResult = ((dtOne).Intersect((dtTwo))).ToList();

How can I find the matching values? 如何找到匹配的值?

Intersect does not work here because on DataRow it just compares references. Intersect在这里不起作用,因为在DataRow它仅比较引用。 Because all rows are different references you get an empty list. 由于所有行都是不同的引用,因此您将获得一个空列表。 Instead you want to compare values. 相反,您想比较值。 Therefore you can use Join . 因此,您可以使用Join But which row do you want to return from both tables? 但是您想从两个表中返回哪一行? If you want both rows you could create an anonymous type of both: 如果您希望两行都可以创建两者的匿名类型:

var objJoinResult = from rowItem in dt_Item.AsEnumerable()
                    join rowSysRole in dt2_SysRole.AsEnumerable()
                    on rowItem.Field<string>("ColumnName") equals rowSysRole.Field<string>("ColumnName")
                    select new { rowItem, rowSysRole };

Output: 输出:

foreach (var both in objJoinResult)
{ 
    Console.WriteLine("rowItem:{0} rowSysRole:{1}", 
        string.Join(",", both.rowItem.ItemArray),
        string.Join(",", both.rowSysRole.ItemArray));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM