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()运算符的示例,用于从列表/集合中获取唯一指定类型的元素。
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 IEnumerableresult = 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.
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)