个性化阅读
专注于IT技术分析

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

在上面的示例中, 我们从”结果”列表中尝试仅获取那些元素, 它们是字符串的类型。最后一个元素将被忽略, 因为它是一个整数。

输出

LINQ OfType()方法

赞(0)
未经允许不得转载:srcmini » LINQ OfType()方法

评论 抢沙发

评论前必须登录!