开发者

LINQ: why does this query not work on an ArrayList?

开发者 https://www.devze.com 2022-12-22 20:55 出处:网络
public staticArrayListGetStudentAsArrayList() { ArrayListstudents = new ArrayList { new Student() { Ro开发者_运维技巧llNumber = 1,Name =\"Alex \" , Section = 1 ,HostelNumber=1 },
public static  ArrayList   GetStudentAsArrayList()
{
    ArrayList  students = new ArrayList
    {
        new Student() { Ro开发者_运维技巧llNumber = 1,Name ="Alex " , Section = 1 ,HostelNumber=1 },
        new Student() { RollNumber = 2,Name ="Jonty " , Section = 2 ,HostelNumber=2 }
    };
    return students;
}

The following code doesn't compile. The error is ArrayList 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 anybody explain what the difference is between these two snippets? Why the second works?


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

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

Consider using List<> instead of ArrayList.


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

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


The array list is untyped so you have to define what type you expect. Use the List class which is strongly typed with generics.

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


Note that the error I get for your snippet is:

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

So I believe an alternative solution (almost definitely not a better one mind you) is to define a Select Extension method for ArrayList.

I guess the different error is due to other namespaces included.


ArrayList.Cast().Select()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号