Cast和ofType的使用转换成IEnumerable类型

其实并不是所有的集合类型数据都支持IEnumerable,比如我们的ArrayList。那么如果我们需要对ArrayList进行linq查询的话,怎么办?这个时候我们可以使用Cast和OfType操作符转换成IEnumerable<T>序列。

也可以使用OfType也可以实现这样的功能

static void Main(string[] args)
{
    ArrayList arrayList = new ArrayList();
    arrayList.Add("one");
    arrayList.Add("two");
    arrayList.Add("three");
    IEnumerable<string> times = arrayList.OfType<string>().Where(n => n.Length <= 3);
    foreach (var item in times)
    {
        Console.WriteLine(item);
    }
    Console.ReadKey();
}Code language: JavaScript (javascript)

他们之间的区别是Cast可以把集合中的每个元素转换为将要放到输出序列中的指定类型,比如这里转换为string,如果有一个不能转换为string,则会抛出异常。而OfType只把可以转换的元素放到序列中,不能转换的跳过。

比如如果我们如果改成这样,则存在无法转换为int类型的变量,于是报错了。

static void Main(string[] args)
{
    ArrayList arrayList = new ArrayList();
    arrayList.Add("one");
    arrayList.Add(56);
    arrayList.Add("three");
    arrayList.Add(23);
    arrayList.Add("three");
    arrayList.Add("556");
    IEnumerable<int> times = arrayList.OfType<int>().Where(n => n <= 100).Select(n => n);
    foreach (var item in times)
    {
        Console.WriteLine(item);
    }
    Console.ReadKey();
}Code language: JavaScript (javascript)

注意,”556″并不是能转换为int,这里不是说这样的转换,而是类型上面是同一个类型。

优先使用OfType而不是Cast,如果需要数据完整性,则可以使用Cast,但是记得要进行trycatch。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注