C# 從集合A中取出集合B中不包含的數據(根據ID判斷),並添加到集合B中

從一個集合A中取出另外一個集合B中不包含的數據,並添加到集合B中spa

 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類以下:code

 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 }
相關文章
相關標籤/搜索