前言
在批量编辑一个列表时候,在编辑时候,如有删除操作,在点击保存时候,会把剩余条目传给后台,那么所剩余的条目就需要与现有数据库中的条目做对比,然后把数据库中的数据删除掉,具体操作如下
实现方法
需求说明:把stu1中不同于stu2的数据排除掉
方法说明:
1、Student为实体类
2、stu1可以理解为现有数据库中所有的数据(sql数据库中现有数据)
3、stu2可以理解为编辑之后所保留的数据(编辑后传到后台的数据)
4、方式一:通过Except方法
5、方式二:通过Contains方法
//实体类
public class Student
{
[Key]
public int ID { get; set; }
public string name { get; set; }
public string age { get; set; }
}
//具体实现
#region 测试
List<Student> stus1 = new List<Student>()
{
new Student(){ ID=1,name="用户1", age="18"},
new Student(){ ID=2,name="用户2", age="18"},
new Student(){ ID=3,name="用户3", age="18"},
new Student(){ ID=4,name="用户4", age="18"},
new Student(){ ID=5,name="用户5", age="18"}
};
List<Student> stus2 = new List<Student>()
{
new Student(){ ID=1,name="用户1", age="18"},
new Student(){ ID=2,name="用户2", age="18"},
new Student(){ ID=3,name="用户3", age="18"},
};
//方式一:通过Except方法
//通过学生的name排除重复项后,执行保留结果为:["用户4","用户5"]
IEnumerable<String> eretainStus1 = (from p in stus1 select p.name).Except(from p in stus2 select p.name);
foreach (var item in eretainStus1)
{
Console.WriteLine("通过Except(学生的name)方法保留学生:" + item);
}
//方式二:利用Contains来比较
//通过学生的name排除重复项后,执行保留结果为:["用户4","用户5"]
IEnumerable<String> cretainStus1 = from p in stus1 where !(from pp in stus2 select pp.name).Contains(p.name) select p.name;
foreach (var item in cretainStus1)
{
Console.WriteLine("利用Contains来比较(学生的name)保留学生:" + item);
}
#endregion
效果截图