如何在两个数据表上将linq查询的结果转换为C#Winforms中的最终数据表

时间:2018-09-07 12:23:35

标签: c# winforms linq

我有两个数据表,一个存储与某些事件详细信息有关的信息,另一个包含用户信息详细信息。 这两个表是:-

  1. 事件详细信息enter image description here

  2. 用户详细信息enter image description here

现在,当我使用linq查询向左使用ack_by等于user_id的用户详细信息表将事件详细信息表与用户详细信息表连接在一起时,便可以正确执行linq查询,但是现在我想将linq查询结果转换回另一个数据表,该怎么做

我的linq查询代码是这样的:-

DataTable recordsDetails = (DataTable)(arrayList)[0];
        DataTable userDetailsTable = (DataTable)(arrayList)[2];            
        var query = (from dt1row in recordsDetails.AsEnumerable()
                    join dt2row in userDetailsTable.AsEnumerable() on dt1row.Field<int>("ack_by") equals dt2row.Field<int>("user_id")                      
                    select new 
                    {
                      event_name = dt1row.Field<string>("event_name"),
                      event_id = dt1row.Field<int>("event_id"),
                      event_severity = dt1row.Field<int>("event_severity"),
                      event_time = dt1row.Field<DateTime>("event_time"),
                      ack_by = dt1row.Field<int>("ack_by"),
                      ack_time = dt1row.Field<DateTime>("ack_time"),
                      zone_id = dt1row.Field<string>("zone_id"),
                      camera_id = dt1row.Field<int>("camera_id"),
                      camera_name = dt1row.Field<string>("camera_name"),
                      user_name = dt2row.Field<string>("username")
                    });

我的问题很简单,如何将linq操作的结果返回到另一个数据表中。 谢谢!

1 个答案:

答案 0 :(得分:0)

IEnumerable<DataRow> query = (from dt1row in recordsDetails.AsEnumerable()
join dt2row in userDetailsTable.AsEnumerable() on dt1row.Field<int>("ack_by") equals dt2row.Field<int>("user_id")                      
select new 
{
  event_name = dt1row.Field<string>("event_name"),
  event_id = dt1row.Field<int>("event_id"),
  event_severity = dt1row.Field<int>("event_severity"),
  event_time = dt1row.Field<DateTime>("event_time"),
  ack_by = dt1row.Field<int>("ack_by"),
  ack_time = dt1row.Field<DateTime>("ack_time"),
  zone_id = dt1row.Field<string>("zone_id"),
  camera_id = dt1row.Field<int>("camera_id"),
  camera_name = dt1row.Field<string>("camera_name"),
  user_name = dt2row.Field<string>("username")
});

DataTable Table = query.CopyToDataTable<DataRow>();