Linq OfType()方法

Linq OfType()方法 首页 / LinQ入门教程 / Linq OfType()方法

OfType()运算符用于返回特定类型的元素,列表/集合中的另一个元素将被忽略。

LINQ OfType()运算符的语法

使用OfType()LINQ运算符的语法是从列表/集合获取指定类型的元素为:

无涯教程网

C#代码

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

In the above syntax, we are trying to get only the string elements from the collection of "obj" by using the OfType operator.

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 result = obj.OfType();
    //foreach loop is applied to print the value of the item
            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
                Console.ReadLine();
        }
    }
}

In the above example, from "result" list, we are trying to get only those elements, which are the type of string. The last element is ignored because it is an integer.

输出:

LINQ OfType() Method




祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

人工智能基础课 -〔王天一〕

微信小程序全栈开发实战 -〔李艺〕

实用密码学 -〔范学雷〕

分布式金融架构课 -〔任杰〕

陶辉的网络协议集训班02期 -〔陶辉〕

爆款文案修炼手册 -〔乐剑峰〕

容量保障核心技术与实战 -〔吴骏龙〕

人人都用得上的数字化思维课 -〔付晓岩〕

大型Android系统重构实战 -〔黄俊彬〕

好记忆不如烂笔头。留下您的足迹吧 :)