OfType的用法

来源:互联网 发布:linux物理内存分配 编辑:程序博客网 时间:2024/06/05 03:53
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication2{    class Program    {        static void Main(string[] args)        {            List<object> fruits = new List<object>(4);            fruits.Add("Mango");            fruits.Add("Orange");            fruits.Add("Apple");            fruits.Add(3.0);            fruits.Add("Banana");            // Apply OfType() to the ArrayList.            IEnumerable<string> query1 = fruits.OfType<string>();            string outputBlock = "";            outputBlock += "Elements of type 'string' are:" + "\n";            foreach (string fruit in query1)            {                outputBlock += fruit + "\n";            }                      // The following query shows that the standard query operators such as             // Where() can be applied to the ArrayList type after calling OfType().            IEnumerable<string> query2 =                fruits.OfType<string>().Where(fruit => fruit.ToLower().Contains("n"));            outputBlock+= "\nThe following strings contain 'n':" + "\n";            foreach (string fruit in query2)            {                outputBlock += fruit + "\n";            }            Console.WriteLine(outputBlock);            Console.ReadKey();        }    }}

0 0