Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

หา Item ที่อยู่ใน List แตไม่อยู่ใน List อีกอันใน C#

ใช้ LINQ Except() (Set Operator) หรือ Where + All/Any

1. Except() - ใช้กับ Primitive Type ได้ดี

List list1 = new List { "tiger", "lion", "dog" };
List list2 = new List { "tiger", "cat", "deer" };

var diff = list1.Except(list2); // lion, dog

Except() ไม่รองรับ Complex Type ตรงๆ** (ต้อง Implement IEquatable หรือ IEqualityComparer)

2. Where + All - ใช้กับ Complex Type ได้

var list1 = new List { new Fruit { Name="Apple", Size="Small" }, new Fruit { Name="Orange", Size="Small" } };
var list2 = new List { new Fruit { Name="Apple", Size="Small" }, new Fruit { Name="Mango", Size="Small" } };

var diff = list1.Where(f1 => list2.All(f2 => f2.Name != f1.Name));
// Result: Orange

Logic: เลือก f1 จาก list1 ที่ **ทุกตัว** ใน list2 มี Name ต่างจาก f1.Name

สรุป

  • Except(): เร็ว สั้น ใช้กับ Primitive/Simple Type
  • Where + All: ยืดหยุ่น ใช้กับ Complex Type / Custom Comparison