[英]Linq Join datatables on multiple columns
I have a linq statements that takes two datatables and joins them together on the id column of each table. 我有一个linq语句,该语句需要两个数据表并将它们连接到每个表的id列上。 My issue is that sometimes the value that I am joining is in a different column in the datatable and I would like to be able to have the statement as is and to look at the other column as well:
我的问题是,有时我要加入的值在数据表的另一列中,因此我希望能够按原样拥有该语句并查看另一列:
Existing: 现有:
Datatable1.AsEnumerable()
.Join(Datatable2.AsEnumerable(),
dt1Row => Datatable1.Field<string>(rowid),
dt2Row=> Datatable2.Field<string>(rowid),
(dt1Row , dt2Row) => new { dt1Row , dt2Row}).ToList()
.ForEach(o => {
o.dt1Row.SetField(o.dt1Row.Table.Columns["name"].Ordinal, o.dt2Row.Field<string>("name1"));
});
Datatable1.AsEnumerable()
.Join(Datatable2.AsEnumerable(),
//Trying to work out?
( dt1Row => Datatable1.Field<string>("rowid"),
dt2Row=> Datatable2.Field<string>("rowid"))
|| ( dt1Row => Datatable1.Field<string>("rowid"),
dt2Row=> Datatable2.Field<string>("name")),
(dt1Row , dt2Row) => new { dt1Row , dt2Row}).ToList()
.ForEach(o => {
o.dt1Row.SetField(o.dt1Row.Table.Columns["name"].Ordinal, o.dt2Row.Field<string>("name1"));
});
sorry for delay, you can use this approach: 抱歉,您可以使用以下方法:
var dt1 = DataTable1.AsEnumerable();
var dt2 = DataTable2.AsEnumerable();
var query = (from dt1Row in dt1
from dt2Row in dt2
where dt1Row["rowid"] == dt2Row["rowid"] ||
dt1Row["rowid"] == dt2Row["name"]
select new
{
dt1Row,
dt2Row
});
you can use iif
statement: 您可以使用
iif
语句:
.Join(Datatable2.AsEnumerable(),
dt1Row => Datatable1.Field<string>("rowid"),
dt2Row => condition ? Datatable2.Field<string>("rowid") : Datatable2.Field<string>("name"),
(dt1Row , dt2Row) => new { dt1Row , dt2Row})
condition
must return a boolean
value condition
必须返回boolean
值
Added another Linq statement in the Join for Datatable2 using any dt.Any() as the condition 使用任何dt.Any()作为条件在Join for Datatable2中添加了另一个Linq语句
Join(Datatable2.AsEnumerable(),
dt1Row => Datatable1.Field<string>("rowid"),
dt2Row => Datatable1.AsEnumerable.Any(x => x.Field<string>("rowid") == Datatable2.Field<string>("rowid"))
? Datatable2.Field<string>("rowid") : Datatable2.Field<string>("name"),
(dt1Row , dt2Row) => new { dt1Row , dt2Row})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.