using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Sample3 { class Program { static void Main(string[] args) { var student1 = new List<student>(); student1.Add(new student() { name = "張三", subject = "英語", score = 89 }); student1.Add(new student() { name = "李四", subject = "英語", score = 95 }); student1.Add(new student() { name = "王五", subject = "英語", score = 69 }); student1.Add(new student() { name = "李倩", subject = "英語", score = 99 }); var student2 = new List<student>(); student2.Add(new student() { name = "李四", subject = "英語", score = 95 }); student2.Add(new student() { name = "王五", subject = "數學", score = 69 }); student2.Add(new student() { name = "趙六", subject = "數學", score = 100 }); //var exp1 = student1.Where(a => student2.Any(t => a.name.Contains(t.name))).ToList(); //使用Exists同樣可以實現 字面上應該更好理解,而且效率要高些 var exp1 = student1.Where(a => student2.Exists(t => a.name.Contains(t.name))).ToList(); Console.WriteLine("--查找student1和student2總同時存在的數據--"); foreach (var item in exp1) { Console.WriteLine("{0} \t {1} \t {2}", item.name, item.subject, item.score); } //var exp2 = student1.Where(a => student2.All(t => !a.name.Contains(t.name))).ToList(); //使用Exists同樣可以實現 字面上應該更好理解,而且效率要高些 var exp2 = student1.Where(a => !student2.Exists(t => a.name.Contains(t.name))).ToList(); Console.WriteLine("--查找student1集合中存在,而student2不存在的數據--"); foreach (var item in exp2) { Console.WriteLine("{0} \t {1} \t {2}", item.name, item.subject, item.score); } Console.Read(); /* --查找student1和student2總同時存在的數據-- 李四 英語 95 王五 英語 69 --查找student1集合中存在,而student2不存在的數據-- 張三 英語 89 李倩 英語 99 */ } } public class student { /// <summary> /// 姓名 /// </summary> public string name; /// <summary> /// 科目 /// </summary> public string subject; /// <summary> /// 分數 /// </summary> public int score; } }