If the value in
DataTable1
is to be replaced with the matching value from
DataTable2
, then the following code can be used
foreach(DataRow row in DataTable1.Rows){
DataRow[] rows2 = DataTable2.Select(string.Format("Id='{0}' and ProductId = '{1}'",row["Id"],
row["ProductId"]));
if (rows2.Length > 0) {
row["Value"]=rows2[0]["Value"];
}
}
For a quick test, paste the following code
void Main()
{
DataTable DataTable1 = new DataTable("DataTable1");
DataTable1.Columns.Add("Id",typeof(string));
DataTable1.Columns.Add("ProductId",typeof(string));
DataTable1.Columns.Add("Value",typeof(string));
DataTable1.Rows.Add("10C","1","10");
DataTable1.Rows.Add("10C","2","20");
DataTable1.Rows.Add("10C","3","30");
DataTable1.Rows.Add("20C","1","10");
DataTable1.Rows.Add("20C","2","20");
DataTable1.Rows.Add("20C","3","30");
DataTable DataTable2 = new DataTable("DataTable2");
DataTable2.Columns.Add("Id",typeof(string));
DataTable2.Columns.Add("ProductId",typeof(string));
DataTable2.Columns.Add("Value",typeof(string));
DataTable2.Rows.Add("10C","1","100");
DataTable2.Rows.Add("10C","2","200");
DataTable2.Rows.Add("10C","3","300");
foreach(DataRow row in DataTable1.Rows){
DataRow[] rows = DataTable2.Select(string.Format("Id='{0}'
and ProductId = '{1}'",row["Id"],row["ProductId"]));
if (rows.Length > 0) {
row["Value"]=rows[0]["Value"];
}
}
DataTable1.Dump();
}
in
LINQPad
, which can be downloaded from here
http://www.linqpad.net/[
^], select
C# Program
in Language combo box and run the program.