C# LINQ Inner Join DataTable 方法

 
C# LINQ Inner Join DataTable 方法
 

 
   using System.Linq;
   using System.Data;
   using System.Data.DataSetExtensions;
 
   function DataTableInnerJoin(){
 
      DataTable dt1 = new DataTable();
      dt1.Columns.Add("CustID", typeof(int));
      dt1.Columns.Add("ColX", typeof(int));
      dt1.Columns.Add("ColY", typeof(int));
 
      DataTable dt2 = new DataTable();
      dt2.Columns.Add("CustID", typeof(int));
      dt2.Columns.Add("ColZ", typeof(int));
 
      for (int i = 1; i <= 5; i++)
      {
         DataRow row = dt1.NewRow();
         row["CustID"] = i;
         row["ColX"] = 10 + i;
         row["ColY"] = 20 + i;
         dt1.Rows.Add(row);
 
         row = dt2.NewRow();
         row["CustID"] = i;
         row["ColZ"] = 30 + i;
         dt2.Rows.Add(row);
      }
 
      var results =
      from table1 in dt1.AsEnumerable()
      join table2 in dt2.AsEnumerable()
      on (int)table1["CustID"] equals (int)table2["CustID"]
      select new
      {
         CustID = (int)table1["CustID"],
         ColX = (int)table1["ColX"],
         ColY = (int)table1["ColY"],
         ColZ = (int)table2["ColZ"]
      };
 
      foreach (var item in results)
      {
         lbl.Text = "";
         lbl.Text += item.CustID;
         lbl.Text += "&nbsp;&nbsp;";
 
         lbl.Text += item.ColX;
         lbl.Text += "&nbsp;&nbsp;";
 
         lbl.Text += item.ColY;
         lbl.Text += "&nbsp;&nbsp;";
 
         lbl.Text += item.ColZ;
         lbl.Text += "<br />";
      }
 
   }