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

เมธอด Linq Except ใน C#


ภาพรวม

เมธอด Except() ใน LINQ ใช้หา ความต่างของเซต (set difference) คืนค่าองค์ประกอบที่อยู่ในลำดับแรก แต่ไม่อยู่ในลำดับที่สอง (ลบซ้ำอัตโนมัติ)

รูปแบบการใช้งาน

int[] arr1 = { 5, 10, 15, 20, 35, 40 };
int[] arr2 = { 20, 35 };
var diff = arr1.AsQueryable().Except(arr2); // {5, 10, 15, 40}

ตัวอย่างโค้ดเต็ม

using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[] arr = { 5, 10, 15, 20, 35, 40 };
        int[] except = { 20, 35 };
        Console.WriteLine("Initial List...");
        foreach (int ele in arr) Console.WriteLine(ele);
        IEnumerable res = arr.AsQueryable().Except(except);
        Console.WriteLine("New List...");
        foreach (int a in res) Console.WriteLine(a);
    }
}

ผลลัพธ์

Initial List...
5
10
15
20
35
40
New List...
5
10
15
40

ข้อสังเกตเพิ่มเติม

  • ใช้การเปรียบเทียบแบบค่าเริ่มต้น (default equality comparer)
  • สำหรับออบเจ็กต์ที่ซับซ้อน ให้ใช้ overload ที่รับ IEqualityComparer<T>
  • ผลลัพธ์ไม่มีลำดับเฉพาะเจาะจง (unordered) หากต้องการเรียง ให้เพิ่ม .OrderBy(x => x)