从两个数据表中选择匹配和不匹配的行

时间:2014-01-27 09:40:03

标签: c# linq ado.net

我有两个数据表dtAllTicket(ticket_id, name)dtSpecialTicket(ticket_id)

首先,我要检索dtAllTicket中的所有行,其中ticket_id中不存在dtSpecialTicket

然后,我想从dtSpecialTicket检索所有行,其中两个表中都存在ticket_id

2 个答案:

答案 0 :(得分:1)

您可以使用Linq-To-DataSetEnumerable.Join,例如:

var specialInBoth = from rowSpecial in dtSpecialTicket.AsEnumerable()
                    join rowAll in dtAllTicket.AsEnumerable()
                    on rowSpecial.Field<int>("ticket_id") equals rowAll.Field<int>("ticket_id") 
                    select rowSpecial;

var specialIDs = new HashSet<int>(dtSpecialTicket.AsEnumerable()
    .Select(row => row.Field<int>("ticket_id")));
var allNotInSpecial = from rowAll in dtAllTicket.AsEnumerable()
                      let id = rowAll.Field<int>("ticket_id") 
                      where !specialIDs.Contains(id)
                      select rowAll;

答案 1 :(得分:0)

var dtUpdate = new HashSet<int>(_dtTicket.AsEnumerable()
                        .Select(row => row.Field<int>("ticket_id")));

var varUnmatched = from all in _sourceDataTable.AsEnumerable()
                   let id = all.Field<int>("ticket_id")
                   where !dtUpdate.Contains(id)
                   select all;
DataTable dtInsert = varUnmatched.CopyToDataTable();

var varMatched = from all in _sourceDataTable.AsEnumerable()
                 let id = all.Field<int>("ticket_id")
                 where dtUpdate.Contains(id)
                 select all;
DataTable dtDelete = varMatched.CopyToDataTable();