當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


LINQ OfType()用法及代碼示例

OfType() 運算符用於返回特定類型的元素,另一個元素將從列表/集合中被忽略。

LINQ OfType() 運算符的語法

使用 OfType() LINQ 運算符從列表/集合中獲取指定類型元素的語法是:

C# 代碼

IEnumerable<string> result = obj.OfType<string>();

在上麵的語法中,我們嘗試使用 OfType 運算符僅從 "obj" 的集合中獲取字符串元素。

LINQ OfType () 運算符示例

這是 LINQ OfType() 運算符的示例,用於從列表/集合中獲取唯一指定類型的元素。

using System;
using System. Collections;
using System.Collections.Generic;
using System.Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
//Create an object of ArrayList and add the values
            ArrayList obj = new ArrayList();
            obj.Add("Australia");
            obj.Add("India");
            obj.Add("UK");
            obj.Add("USA");
            obj.Add(1);
//ofType() method will return the value only the specific type
            IEnumerable<string> result = obj.OfType<string>();
    //foreach loop is applied to print the value of the item
            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
                Console.ReadLine();
        }
    }
}

在上麵的例子中,從 "result" 列表中,我們試圖隻獲取那些字符串類型的元素。最後一個元素被忽略,因為它是一個整數。

輸出:

LINQ OfType() Method



相關用法


注:本文由純淨天空篩選整理自 LINQ OfType() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。