如何比较相同格式的两个数据表之间的差异?

时间:2013-09-24 09:29:39

标签: c# linq datatable

我有两个数据表具有相同的列数。我必须检查哪个名称在新数据表中具有不同的组或子组。(Using Linq

DataTableOLD

CODE    NAME    GROUP   SUBGROUP
c1      AA      GP1     SGP1
c2      BB      GP1     SGP1
c3      CC      GP1     SGP2
c4      DD      GP1     SGP2
c5      EE      GP2     SGP3


DataTableNEW
CODE    NAME    GROUP   SUBGROUP
c1      AA      GP1     SGP4
c2      BB      GP1     SGP1
c3      CC      GP3     SGP5
c4      DD      GP1     SGP2
c6      FF      GP2     SGP3


Resultant table (show only those where there is mismatch in either group or group and subgroup both)

OLDCODE OLDNAME OLDGROUP OLDSUBGROUP  NEWCODE NEWNAME NEWGROUP NEWSUBGROUP
c1      AA      GP1         SGP1        c1      AA      GP1     SGP4
c3      CC      GP1         SGP2        c3      CC      GP3     SGP5

1 个答案:

答案 0 :(得分:1)

var lstResult = (from _old in DataTableOLD.AsEnumerable()
    join _new in DataTableNew.AsEnumerable() on _old.Field<string>("CODE") 
      equals _new.Field<string>("CODE")
    where _old.Field<string>("GROUP") != _new.Field<string>("GROUP") ||
    _old.Field<string>("SUBGROUP") != _new.Field<string>("SUBGROUP")
    select new
    {
        OLDCODE = _old.Field<string>("CODE"),
        OLDNAME = _old.Field<string>("NAME"),
        OLDGROUP = _old.Field<string>("GROUP"),
        OLDSUBGROUP = _old.Field<string>("SUBGROUP"),
        NEWCODE = _new.Field<string>("CODE"),
        NEWNAME = _new.Field<string>("NAME"),
        NEWGROUP = _new.Field<string>("GROUP"),
        NEWSUBGROUP = _new.Field<string>("SUBGROUP")
     }
);