Objective
In this article, I am going to show, how we could apply LINQ to query non-IEnumerable<T> Collections.
I have created a class for my explanation purpose. Student class is having details of students.
Student.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace LINQtoOBJECT1
7 {
8 public class Student
9 {
10
11 public int RollNumber { get; set; }
12 public string Name { get; set; }
13 public int Section { get; set; }
14 public int HostelNumber { get; set; }
15 }
16 }
17
To create ArrayList of Student, I am creating a static function. This static function will return ArraList of student.
Function to return ArrayList of students.
1 public static ArrayList GetStudentAsArrayList()
2 {
3
4 ArrayList students = new ArrayList
5 {
6 new Student() { RollNumber = 1,Name =“Alex “ , Section = 1 ,HostelNumber=1 },
7 new Student() { RollNumber = 2,Name =“Jonty “ , Section = 2 ,HostelNumber=2 },
8 new Student() { RollNumber = 3,Name =“Samba “ , Section = 3 ,HostelNumber=1 },
9 new Student() { RollNumber = 4,Name =“Donald “ , Section = 3 ,HostelNumber=2 },
10 new Student() { RollNumber = 5,Name =“Kristen “ , Section = 2 ,HostelNumber=1 },
11 new Student() { RollNumber = 6,Name =“Mark “ , Section = 1 ,HostelNumber=2},
12 new Student() { RollNumber = 7,Name =“Gibbs “ , Section = 1 ,HostelNumber=1 },
13 new Student() { RollNumber = 8,Name =“Peterson “ , Section = 2 ,HostelNumber=2 },
14 new Student() { RollNumber = 9,Name =“collingwood “ , Section = 3 ,HostelNumber=1 },
15 new Student() { RollNumber = 10,Name =“Brian “ , Section = 3 ,HostelNumber=2 }
16
17 };
18
19 return students;
20
21 }
Now when I tried to query the returned ArrayList using LINQ, I got compile time error. Because ArrayList does not implement interface IQueryable and it is not IEnumerable<T> collection.
Below code gave a compile time error
1 ArrayList lstStudents = GetStudentAsArrayList();
2 var res = from r in lstStudents select r;
Error is as below,
Above error cause because LINQ by default only query against IEnumerable<T> collections.
So , how to query an ArrayList? Here Range variable comes into action. If I modify the above query as below , I would be able to query LINQ against a non IEnumerable<T> collection.
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Collections;
6
7
8 namespace LINQtoOBJECT1
9 {
10 class Program
11 {
12 static void Main(string[] args)
13 {
14
15
16 ArrayList lstStudents = GetStudentAsArrayList();
17 var res = from Student r in lstStudents select r;
18 foreach (Student s in res)
19 {
20 Console.WriteLine(s.Name);
21 }
22
23 Console.ReadKey();
24
25
26
27 }
I am using Student as range variable. And we will get output as below .In above code I am using Student the class in ArrayList as range variable.
Conclusion
In this article, I discussed how to query against non IEnumerable<T> collection. Thanks for reading.
Leave a Reply