Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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 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?

like image 288
Benny Avatar asked Mar 16 '10 05:03

Benny


People also ask

Can we use LINQ on ArrayList?

LINQ with ArrayListYou don't need to specify array size unlike traditional array and the size grows as you will add more element into it. However, it is slower than Array but it is more useful when you work with collection. Here, in this example, we will learn how to process data in ArrayList using LINQ C#.

How do I select a query in LINQ?

LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.

Is LINQ inefficient?

Conclusion. It would seem the performance of LINQ is similar to more basic constructs in C#, except for that notable case where Count was significantly slower. If performance is important it's crucial to do benchmarks on your application rather than relying on anecdotes (including this one).


2 Answers

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.

like image 75
p.campbell Avatar answered Sep 23 '22 01:09

p.campbell


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>();
like image 29
lesscode Avatar answered Sep 24 '22 01:09

lesscode