Linq是Language Integrated Query的简称,它是微软在.NET Framework 3.5里面新加入的特性,用以简化查询查询操作。本文主要介绍.NET(C#) 中Linq的Cast和OfType操作符。

1、Cast操作符

Cast操作符用于将一个类型为IEnumerable的集合对象转换为IEnumerable<T>类型的集合对象。也就是非泛型集合转成泛型集合,因为在Linq to OBJECT中,绝大部分操作符都是针对IEnumerable<T>类型进行的扩展方法。因此对非泛型集合并不适用。

例如,

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
           ArrayList al = new ArrayList();
            al.Add(1);
            al.Add(2);
            al.Add(3);
            IEnumerable<int> IEInt = al.Cast<int>();    //非泛型转泛型
            foreach (var i in IEInt)
            {
                Console.WriteLine(i);           
            }
            Console.ReadKey();
        }
    }
}

2、OfType操作符

OfType操作符与Cast操作符类似,用于将类型为IEnumerable的集合对象转换为IEnumerable<T>类型的集合对象。不同的是,Cast操作符会视图将输入序列中的所有元素转换成类型为T的对象,,如果有转换失败的元素存在Cast操作符将抛出一个异常;而OfType操作符仅会将能够成功转换的元素进行转换,并将这些结果添加到结果序列中去。与Cast操作符相比,OfType操作符更加安全。

例如,

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList al = new ArrayList();
            al.Add(1);
            al.Add(2);
            al.Add("a");
            //IEnumerable<int> IECast = al.Cast<int>();    //抛出异常
            //foreach (var i in IECast)
            //{
            //    Console.WriteLine(i);
            //}
            IEnumerable<int> IEOfType = al.OfType<int>();
            foreach (int i in IEOfType)
            {
                Console.WriteLine(i);   //输出 1 2 其中转换不了的a则不转换            
            }
            Console.ReadKey();
        }
    }
}

推荐文档