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

最基本的写法无非是写多层foreach循环,数据量多了,循环的次数是乘积增长的。

这里推荐使用Except()差集、Intersect()交集,具体性能没有进行对比。

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

//与免打扰中的用户进行比较,筛选出可以正常接收推送的用户
var normalReceive = dtUser.AsEnumerable().Except(dtDND.AsEnumerable(), DataRowComparer.Default);

//比对两个表的用户名一致的,保存username到list中
var intersectUser = dtUserPower.AsEnumerable().Intersect(normalReceive, DataRowComparer.Default);


  
foreach (var item in intersectUser)
{
listTemp.Add(item["username"].ToString());
}

如果两个datatable中有部分字段相同,也就是说有可进行比对的字段的话。

//与免打扰中的用户进行比较,筛选出可以正常接收推送的用户
var normalReceive = from r in dtUser.AsEnumerable()
where
!(from rr in dtDND.AsEnumerable() select rr.Field<string>("username")).Contains(
r.Field<string>("username"))
select r;

//比对两个表的用户名一致的,保存token到list中
var intersectUser = from r in normalReceive.AsEnumerable()
where
(from rr in dtUserPower.AsEnumerable() select rr.Field<string>("username")).Contains(
r.Field<string>("username"))
select r;

foreach (var item in intersectUser)
{
listTemp.Add(item["token"].ToString());
}

猜你喜欢

转载自www.cnblogs.com/jjj250/p/10551232.html