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

เมธอด OfType() ใน C#

เมธอด OfType<T>() ใช้กรององค์ประกอบในคอลเลกชันที่ไม่มีชนิดข้อมูลเฉพาะ (Non-generic collection เช่น ArrayList) เพื่อคืนค่าลำดับที่มีเฉพาะชนิด T ที่ต้องการ

ตัวอย่าง: แยก String และ Integer จาก ArrayList

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

public class Demo
{
    public static void Main()
    {
        IList list = new ArrayList();
        list.Add("Katie");
        list.Add(100);
        list.Add(200);
        list.Add(300);
        list.Add(400);
        list.Add("Brad");
        list.Add(600);
        list.Add(700);

        var myStr = from a in list.OfType() select a;
        var myInt = from a in list.OfType() select a;

        Console.WriteLine("Strings...");
        foreach (var strVal in myStr) Console.WriteLine(strVal);

        Console.WriteLine("Integers...");
        foreach (var intVal in myInt) Console.WriteLine(intVal);
    }
}

ผลลัพธ์

Strings...
Katie
Brad
Integers...
100
200
300
400
600
700

ประโยชน์: ช่วยให้ทำงานกับคอลเลกชันแบบเก่า (Non-generic) ได้อย่างปลอดภัยและสะดวก โดยไม่ต้อง Cast เอง