我们在开发过程中,比较经常需要对比两个List对象的对象的条数据,找出新增、找出删除、新增更改的删除条目。典型的更改情况如需要根据前端给出的云服务器提供商请求列表,与后台表中当前具有的比较记录做比较,然后对后台表做增、对象的条删、找出改的新增操作。为此,云南idc服务商删除以下举例总结List对象的更改比对方法。
新建一个控制台程序新建一个控制台程序作为例子。比较
定义一个记录数据条目的对象的条类publicclassClass1{ publicstringId{ get;set;}publicstringRes{ get;set;}} 构建两个List对象List<Class1> listA =newList<Class1>{ newClass1{ Id="1001",Res="A1"},newClass1{ Id="1002",Res="A2"},newClass1{ Id="1003",Res="A3"}};List<Class1> listB =newList<Class1>{ newClass1{ Id="1001",Res="B1"},newClass1{ Id="1002",Res="B2"},newClass1{ Id="1004",Res="B3"},newClass1{ Id="1005",Res="B4"},}; 两个List对象条目做比对// 从listB中找出相对listA新增的var queryInsert = listB.Where(b =>{ if(!listA.Any(a => a.Id== b.Id))returntrue;returnfalse;}).ToList(); queryInsert.ForEach(q =>{ WriteLine("新增项:"+ q.Id+", "+ q.Res);});WriteLine();// 从listA中找出相对listB删除的var queryDelete = listA.Where(a =>{ if(listB.All(b => b.Id!=a.Id))returntrue;returnfalse;}).ToList(); queryDelete.ForEach(q =>{ WriteLine("删除项:"+ q.Id+", "+ q.Res);});WriteLine();// 从listB中找出相对listA更新的var queryUpdate = listB.Where(b =>{ if(listA.Any(a => a.Id== b.Id))returntrue;returnfalse;}).ToList(); queryUpdate.ForEach(q =>{ WriteLine("更新项:"+ q.Id+", "+ q.Res);}); 输出结果