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

โปรแกรม C# สำหรับหาความแตกต่างระหว่างสองลิสต์

ภาพรวม

บทความนี้สาธิตวิธีใช้เมธอด Except() จาก LINQ เพื่อหาความแตกต่างระหว่างสองลิสต์ (รายการที่อยู่ในลิสต์แรกแต่ไม่อยู่ในลิสต์ที่สอง)

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

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

public class Demo {
    public static void Main() {
        List<string> list1 = new List<string> { "A", "B", "C", "D" };
        List<string> list2 = new List<string> { "C", "D" };

        Console.WriteLine("First list...");
        list1.ForEach(Console.WriteLine);

        Console.WriteLine("Second list...");
        list2.ForEach(Console.WriteLine);

        IEnumerable<string> list3 = list1.Except(list2);

        Console.WriteLine("Difference in the two lists...");
        list3.ToList().ForEach(Console.WriteLine);
    }
}

ผลลัพธ์

First list...
A
B
C
D
Second list...
C
D
Difference in the two lists...
A
B

คำอธิบาย

  • Except() คืนค่าองค์ประกอบที่อยู่ในลิสต์แรกแต่ไม่อยู่ในลิสต์ที่สอง
  • ต้องมี using System.Linq;
  • ผลลัพธ์เป็น IEnumerable<T> สามารถแปลงเป็นลิสต์ได้ด้วย .ToList()
  • เมธอดนี้ใช้การเปรียบเทียบค่าเริ่มต้น (default equality comparer)