LINQ:为什么此查询不适用于ArrayList? [英] LINQ: why does this query not work on an ArrayList?

查看:52
本文介绍了LINQ:为什么此查询不适用于ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static  ArrayList   GetStudentAsArrayList()
{
    ArrayList  students = new ArrayList
    {
        new Student() { RollNumber = 1,Name ="Alex " , Section = 1 ,HostelNumber=1 },
        new Student() { RollNumber = 2,Name ="Jonty " , Section = 2 ,HostelNumber=2 }
    };
    return students;
}

以下代码无法编译.错误是ArrayList is not IEnumerable

The following code doesn't compile. The error is ArrayList is not IEnumerable

ArrayList lstStudents = GetStudentAsArrayList();
var res = from r in lstStudents select r;  

它将编译:

ArrayList lstStudents = GetStudentAsArrayList();
var res = from  Student   r in lstStudents select r;

有人可以解释这两个摘要之间的区别吗?为什么第二个有效?

Can anybody explain what the difference is between these two snippets? Why the second works?

推荐答案

由于ArrayList允许您收集不同类型的对象,因此编译器不知道它需要对哪种类型进行操作.

Since ArrayList allows you to collect objects of different types, the compiler doesn't know what type it needs to operate on.

第二个查询显式强制转换ArrayList中的每个对象以键入Student.

The second query explicitly casts each object in the ArrayList to type Student.

考虑使用List<>而不是ArrayList.

Consider using List<> instead of ArrayList.

这篇关于LINQ:为什么此查询不适用于ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆