C# 从集合A中取出集合B中不包含的数据(根据ID判断),并添加到集合B中
从一个集合A中取出另一个集合B中不包含的数据,并添加到集合B中
1 private void button2_Click(object sender, EventArgs e) 2 { 3 var ListA = new List<student>(); 4 ListA.Add(new student() { name = "张三", subject = "英语", score = 89 }); 5 ListA.Add(new student() { name = "李四", subject = "英语", score = 951 }); 6 ListA.Add(new student() { name = "王五", subject = "英语", score = 69 }); 7 ListA.Add(new student() { name = "李倩", subject = "英语", score = 99 }); 8 9 var ListB = new List<student>(); 10 ListB.Add(new student() { name = "李四", subject = "英语", score = 95 }); 11 ListB.Add(new student() { name = "王五", subject = "数学", score = 69 }); 12 ListB.Add(new student() { name = "赵六", subject = "数学", score = 100 }); 13 14 //使用Exists同样可以实现 字面上应该更好理解,而且效率要高些 15 //从ListB中查找ListA中不包含的数据,根据name判断 16 var exp2 = ListB.Where(a => !ListA.Exists(t => a.name.Contains(t.name))).ToList() as List<student>; 17 18 ListA.AddRange(exp2); 19 20 }
Student类如下:
1 public class student 2 { 3 /// <summary> 4 /// 姓名 5 /// </summary> 6 public string name; 7 /// <summary> 8 /// 科目 9 /// </summary> 10 public string subject; 11 /// <summary> 12 /// 分数 13 /// </summary> 14 public int score; 15 }