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?
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#.
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.
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).
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With