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

โปรแกรม C# ดึงองค์ประกอบที่ไม่ซ้ำกันจากลำดับข้อมูล

กำหนดลำดับข้อมูลและเพิ่มสมาชิก:

List<int> ID = new List<int> { 120, 111, 250, 111, 120, 300, 399, 450 };

ใช้เมธอด Distinct() เพื่อดึงองค์ประกอบที่ไม่ซ้ำกันจากลิสต์ข้างต้น:

IEnumerable<int> res = ID.AsQueryable().Distinct();

มาดูโค้ดทั้งหมดกัน

ตัวอย่าง

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

class Demo
{
    static void Main()
    {
        List<int> ID = new List<int> { 120, 111, 250, 111, 120, 300, 399, 450 };
        // ดึงองค์ประกอบที่ไม่ซ้ำกัน
        IEnumerable<int> res = ID.AsQueryable().Distinct();
        
        foreach (int arr in res)
        {
            Console.WriteLine(arr);
        }
    }
}

ผลลัพธ์

120
111
250
300
399
450