dark knight
dark knight

Reputation: 11

Compare two datatables to find matching values

I have 2 data tables. 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?

Upvotes: 0

Views: 2186

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460048

Intersect does not work here because on DataRow it just compares references. Because all rows are different references you get an empty list. Instead you want to compare values. Therefore you can use 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));
}

Upvotes: 3

Related Questions