【发布时间】:2012-10-23 11:24:55
【问题描述】:
我在使用 Linq Join 时遇到问题。我想加入 2 个表,它们具有与 n 列相同的结构。我的问题是我不知道这些列的名称,那么如何在 select new 中重写它们?
表 1:这里我有一些 ID、Name 和 LastName 参数。注释、属性等为空
ID Name LastName Comment Attribute ...
"what" "ABC" ...
"hello" "SDE" ...
3 lola
1 de
4 miki
... ... ... ...
表 2:这里与表 1 相同,但在 Comment、Attribute 和 Rest 中有一些参数。
ID Name LastName Comment Attribute ...
"what" "ABC" ...
"hello" "SDE" ...
1 de "hi"
4 miki "OKK"
3 lola "yo" "LL"
结果:我想加入这样的表格
ID Name LastName Comment Attribute ...
"what" "ABC" ...
"hello" "SDE" ...
3 lola "yo" "LL"
1 de "hi"
4 miki "OKK"
... ... ... ... ... ...
我的代码是:
var Result= from tb1 in table1.AsEnumerable()
join tb2 in tabl2.AsEnumerable()
on new
{
Name = tb1.Field<String>("Name"),
LastName = tb1.Field<String>("LastName"),
} equals new
{
Name=tb2.Field<String>("Name"),
LastName=tb2.Field<String>("LastName"),
}
into grp1
from tb3 in grp1.DefaultIfEmpty()
select new
{
ID = tb1.Field<String>("ID"),
Name = tb1.Field<String>("Name") ,
LastName = tb1.Field<String>("LastName"),
Comment = tb3!= null ? tb3.Field<String>("Comment") : null,
Attribute= tb3!= null ? tb3.Field<String>("Attribute") : null,
...
// Here should be next Columns Name but don't know how to put there
};
我尝试了这段代码,但我的编译器只是挂了,不知道为什么
for (int i = 2; i < table1.Rows.Count; i++)
{
foreach (DataRow dr in table2.Rows)
{
if ((table1.Rows[i]["Name"].ToString() == dr["Name"].ToString())&&table1.Rows[i]["LastName"].ToString() == dr["LastName"].ToString())
{
table1.Rows.RemoveAt(i);
table1.ImportRow(dr);
}
}
}
dataGridView1.DataSource = table1;
【问题讨论】:
-
我想我应该使用 ToDictonary 但不知道如何
-
你为什么不直接返回 tb1 呢?而不是 'select new { ... }' 做 'select tb1' 之类的事情
-
不,选择 tb1 在这里不会做任何事情。首先,我丢失了 table2 的结果,它什么也没显示
-
只是一个问题,为什么需要合并它们? Table2 似乎包含整个 Table1?如果它对你有帮助,你可以看看这个问题stackoverflow.com/questions/725556/…。身份证呢,如果发生冲突,应该如何处理?数据冲突等。
-
我想加入他们,因为我想拥有表 1 中的 ID、Name 和 LastName。在表 2 中,有时 ID、LastName、Name 可能会丢失。这就是我使用外左连接的原因