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

โปรแกรม C# หาค่าที่แตกต่างในสองรายการ

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

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

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

public class Demo
{
    public static void Main()
    {
        List list1 = new List { "P", "Q", "R", "S", "T", "U", "V", "W" };
        List list2 = new List { "T", "U", "V", "W" };
        
        Console.WriteLine("First list: " + string.Join(" ", list1));
        Console.WriteLine("Second list: " + string.Join(" ", list2));
        
        IEnumerable list3 = list1.Except(list2);
        
        Console.WriteLine("Remaining values (in list1 but not list2):");
        foreach (string value in list3) Console.WriteLine(value);
    }
}

ผลลัพธ์

First list: P Q R S T U V W
Second list: T U V W
Remaining values (in list1 but not list2):
P
Q
R
S

หมายเหตุ: Except คืนค่าที่ไม่ซ้ำ (Distinct) และเรียงลำดับตามลำดับแรก