LINQ: why does this request not work in 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;
}

The following code does not compile. MistakeArrayList is not IEnumerable

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

This compiles:

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

Can anyone explain what the difference is between the two fragments? Why does the second work?

+5
source share
5 answers

Since ArrayList allows you to collect objects of different types, the compiler does not know what type it should work on.

The second query explicitly sets each object in the ArrayList to enter Student.

Consider using List<>instead of ArrayList.

+9
source

In the second case, you specify LINQ what the type of collection is. ArrayList is weakly typed, so to use it effectively in LINQ, you can use Cast <T>:

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

, , . List, .

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

Note that the error I get for your snippet is:

Could not find implementation of query template for source type 'System.Collections.ArrayList. "Select" not found. Consider explicitly specifying the type range of the variable "r".

So, I believe that an alternative solution (almost certainly not the best you need) is to define the Select Extension method for ArrayList.

I assume that the other error is related to other included namespaces.

+1
source

ArrayList.Cast().Select()

-1
source

All Articles