gpt4 book ai didi

c# - DataTable Linq 连接多列

转载 作者:行者123 更新时间:2023-11-30 12:31:39 26 4
gpt4 key购买 nike

我在使用 Linq Join 时遇到了问题。我想加入 2 个表,它们与 n 列具有相同的结构。我的问题是我不知道这些列的名称,所以如何在 select new 中重写它们?

表 1:这里我在 ID、Name 和 LastName 中有一些参数。 Comment, Attribute 其余为空

 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;

最佳答案

对于table1中的每个row1,如果table2中有匹配的row2,则使用row2。否则,使用第 1 行。

var newTable = table1.Clone();
foreach (DataRow row1 in table1.Rows) // To skip the first 2, use table1.Rows.Cast<DataRow>().Skip(2)
{
var row = table2.Rows.Cast<DataRow>().FirstOrDefault(row2 =>
row1["Name"].ToString() == row2["Name"].ToString() &&
row1["LastName"].ToString() == row2["LastName"].ToString()) ?? row1;
newTable.ImportRow(row);
}
dataGridView1.DataSource = newTable;

关于c# - DataTable Linq 连接多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13029390/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com