0

Please see the sample below. LINQ expression is asking for the list of Student objects with _Age in between 15 and 20. When I see varlist in debugger, it shows 5 entries. When I print varlist, it prints just one entry, which is correct. Even after Printing, debugger shows 5 entries in varlist. Is this behavior documented any where, please let me know. Should there be lot of entries in the list, like millions, for LINQ expression to actually filter the items.

public class Student
{
    public int StudentID { get; set; }
    public String StudentName { get; set; }
    public int Age { get; set; }
}

static void Main(string[] args)
{
    IList<Student> studentList = new List<Student>
    { 
        new Student { StudentID = 1, StudentName = "John", Age = 13 }, 
        new Student { StudentID = 2, StudentName = "Moin", Age = 21 }, 
        new Student { StudentID = 3, StudentName = "Bill", Age = 18 }, 
        new Student { StudentID = 4, StudentName = "Ram", Age = 20 }, 
        new Student { StudentID = 5, StudentName = "Ron", Age = 15 }
   };

    IEnumerable<Student> varlist = from rv in studentList
                                   where rv.Age > 15 && rv.Age < 20
                                   select rv;
    foreach (Student x in varlist)
    {
        Console.WriteLine("{0} {1}", x.Age, x.StudentName);
    }
}
slugster
  • 49,403
  • 14
  • 95
  • 145
user1174790
  • 309
  • 4
  • 11

2 Answers2

4

This is how the deferred execution works with Linq. The Linq query has an expression tree behind, so you can look at your Linq query as a data structure. Your query does not execute until you request the data, when that expression is compiled, this happens when you are enumerating through it.

You can read more about it here:

http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx

IEnumerable<Customer> query = from customer in db.Customers  << Query does  
        where customer.City == "Paris" << not execute
        select customer;               << here 


foreach (var Customer in query) << Query executes here

No matter you are using an IEnumerable or IQueryable to represent the query variable, both are going to use deferred execution:

Returning IEnumerable<T> vs. IQueryable<T>

Community
  • 1
  • 1
lex87
  • 1,276
  • 1
  • 15
  • 33
1

Idea of LINQ is that you can add operations on top of it before actual execution.

In case you want to force LINQ to calculate result, you can use ToArray().

var arr = seq.ToArray();
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Eckd
  • 358
  • 1
  • 10