我想用 linq 或 DataRelation 加入 2 个表。所以我首先尝试了 linq,它工作得很好,但是当我将另一个对象添加到 1.Tables 并加入 2.Table 时,它不会显示这个对象。
这是我的代码:
DataTable table = new DataTable("Kunde");
table.Columns.Add("KundeID", typeof(Int32));
table.Columns.Add("KundeName", typeof(String));
table.Columns.Add("Produkt", typeof(String));
table.PrimaryKey = new DataColumn[] { table.Columns["KundeID"] };
DataTable comment = new DataTable("Comment");
comment.Columns.Add("KundeName", typeof(String));
comment.Columns.Add("Comment", typeof(String));
comment.PrimaryKey = new DataColumn[] { comment.Columns["KundeName"] };
DataSet ds = new DataSet("DataSet");
ds.Tables.Add(table);
ds.Tables.Add(comment);
object[] o1 = { 1, "Michael", "Jogurt" };
object[] o2 = { 2, "Raj", "Cola" };
object[] o3 = { 3, "Gary", "Fanta" };
***object[] o4 = { 4, "Miky", "Sprite" };***
object[] c1 = { "Raj", "Ich bin cool" };
object[] c2 = { "Gary", "yahoo" };
object[] c3 = { "Michael", "nichts zu verlieren" };
table.Rows.Add(o1);
table.Rows.Add(o2);
table.Rows.Add(o3);
table.Rows.Add(o4);
comment.Rows.Add(c1);
comment.Rows.Add(c2);
comment.Rows.Add(c3);
var results = from table1 in table.AsEnumerable()
join table2 in comment.AsEnumerable()
on table1.Field<string>("KundeName") equals table2.Field<string>("KundeName")
select new
{
KundeID = table1.Field<Int32?>("KundeID"),
KundeName = table1.Field<String>("KundeName"),
Produkt = table1.Field<String>("Produkt"),
Comment = table2.Field<String>("Comment")
};
foreach (var item in results)
{
Console.WriteLine(String.Format("{0} {1} {2} {3}", item.KundeID, item.KundeName, item.Produkt, item.Comment));
}
Console.ReadKey();