Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức OfType() trong LINQ C#

Phương thức OfType<T>() trong LINQ dùng để lọc các phần tử theo kiểu dữ liệu từ một tập hợp không kiểu mạnh (như ArrayList, IList, IEnumerable không generic). Nó chỉ trả về các phần tử có kiểu chính xác là T (hoặc kế thừa từ T).

Ví dụ: Lọc string và int từ ArrayList

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);

// Lọc chỉ string
var myStr = from a in list.OfType() select a;

// Lọc chỉ int
var myInt = from a in list.OfType() select a;

Mã nguồn hoàn chỉnh

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("Chuỗi (string):");
        foreach (var strVal in myStr) Console.WriteLine(strVal);
        
        Console.WriteLine("\nSố nguyên (int):");
        foreach (var intVal in myInt) Console.WriteLine(intVal);
    }
}

Kết quả

Chuỗi (string):
Katie
Brad

Số nguyên (int):
100
200
300
400
600
700

So sánh OfType vs Cast

Phương thứcHành viKhi phần tử sai kiểu
OfType<T>()Lọc, bỏ qua phần tử không phải TBỏ qua im lặng
Cast<T>()Ép kiểu tất cả phần tử sang TNém InvalidCastException

Ứng dụng thực tế

  • Xử lý dữ liệu từ COM, reflection, hoặc API cũ trả về object[]/ArrayList
  • Lọc các control trong WinForms/WPF: Controls.OfType<Button>()
  • Xử lý JSON/XML không kiểu mạnh