代码之家  ›  专栏  ›  技术社区  ›  Benny

Linq:为什么这个查询不能在ArrayList上工作?

  •  7
  • Benny  · 技术社区  · 15 年前
    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;
    

    有人能解释一下这两个片段之间的区别吗?为什么第二个有效?

    5 回复  |  直到 6 年前
        1
  •  9
  •   p.campbell    15 年前

    因为arraylist允许您收集不同类型的对象,所以编译器不知道它需要操作什么类型。

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

    考虑使用 List<> 而不是数组列表。

        2
  •  8
  •   lesscode    6 年前

    在第二种情况下,您将告诉Linq集合的类型。 ArrayList 是弱类型的,因此为了在LINQ中有效地使用它,可以使用 Cast<T> :

    IEnumerable<Student> _set = lstStudents.Cast<Student>();
    
        3
  •  2
  •   ChaosPandion    15 年前

    数组列表是非类型化的,因此您必须定义所需的类型。使用带有泛型的强类型列表类。

    List<Student> lstStudents = GetStudentAsArrayList();
    var res = from  r in lstStudents select r;
    
        4
  •  1
  •   Mark Hurd    15 年前

    请注意,我从您的代码片段中得到的错误是:

    找不到的实现 源类型的查询模式 “System.Collections.ArrayList”。 找不到“select”。考虑 显式指定 范围变量“r”。

    所以我认为另一种解决方案(几乎肯定不是更好的方法)是为arraylist定义一个select扩展方法。

    我想不同的错误是由于包含了其他名称空间。

        5
  •  -1
  •   abilauca    14 年前

    ArrayList.Cast().Select()