C# 两个datatable中的数据快速比较返回交集或差集

转自: https://www.cnblogs.com/lacey/p/5893380.html

如果两个datatable的字段完全一致的话,可以直接使用Except,Intersect

//Except()差集
var tempExcept = dt1.AsEnumerable().Except(dt12.AsEnumerable(), DataRowComparer.Default);

//Intersect()交集
var tempIntersect= dt1.AsEnumerable().Except(dt12.AsEnumerable(), DataRowComparer.Default);

如果两个datatable中有部分字段相同,可以使用Contains比较  

//差集
var tempExcept = from r in dt1.AsEnumerable()
where
!(from rr in dt2.AsEnumerable() select rr.Field<string>("username")).Contains(
r.Field<string>("username"))
select r;

//交集
var tempExcept = from r in dt1.AsEnumerable()
where
(from rr in dt2.AsEnumerable() select rr.Field<string>("username")).Contains(
r.Field<string>("username"))
select r;

猜你喜欢

转载自www.cnblogs.com/douf/p/10019582.html