LINQ:为什么这个查询不适用于ArrayList?

问题描述 投票:7回答:5
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

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

这编译:

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

任何人都可以解释这两个片段之间的区别吗?为什么第二个有效?

c# linq
5个回答
9
投票

由于ArrayList允许您收集不同类型的对象,因此编译器不知道它需要操作什么类型。

第二个查询显式地将ArrayList中的每个对象强制转换为类型Student。

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


8
投票

在第二种情况下,您告诉LINQ该集合的类型是什么。 ArrayList是弱类型的,所以为了在LINQ中有效地使用它,你可以使用Cast<T>

IEnumerable<Student> _set = lstStudents.Cast<Student>();

2
投票

数组列表是无类型的,因此您必须定义所需的类型。使用强类型泛型的List类。

List<Student> lstStudents = GetStudentAsArrayList();
var res = from  r in lstStudents select r;

1
投票

请注意,我为您的代码段获得的错误是:

无法找到源类型“System.Collections.ArrayList”的查询模式的实现。找不到“选择”。考虑明确指定范围变量'r'的类型。

因此,我认为另一种解决方案(几乎肯定不是更好的一种解决方法)是为ArrayList定义一个Select Extension方法。

我猜不同的错误是由于包含其他命名空间。


0
投票

ArrayList.Cast().Select()

© www.soinside.com 2019 - 2024. All rights reserved.