none
EF: How IEnumerable<> works RRS feed

  • Question

  • public IEnumerable<Animals> AllSpotted()
    {
        return from a in Zoo.Animals
               where a.coat.HasSpots == true
               select a;
    }
    

    people saying IEnumerable<> is deferred execution. see the above code and tell me when i will get animal data

    var animal = AllSpotted();

    when i will call AllSpotted() then all data comes from db or only filter data comes from db ? if all data comes then performance will be low am i right ?

    so how to increase performance that i want only only filter data should come from db because i used this filter  where a.coat.HasSpots == true

    i found one good point from https://stackoverflow.com/a/28513685

    Where(x => x.City == "<City>") works on both IEnumerable and IQueryable

    When using Where() on an IEnumerable collection, the compiler passes a compiled function to Where()

    When using Where() on an IQueryable collection, the compiler passes an expression tree to Where(). An expression tree is like the reflection system but for code. The compiler converts your code into a data structure that describes what your code does in a format that's easily digestible.

    please share the knowledge. thanks

    Thursday, March 15, 2018 10:53 AM

Answers

  • Hi Sudip_inn,

    when i will call AllSpotted() then all data comes from db or only filter data comes from db ? if all data comes then performance will be low am i right ?

    As the link mentioned. IEnumerable and IQueryable are deferred execution. so when you call AllSpotted(), it will not be executed in database, it will be executed when the query variable is iterated over and filter data from database. here is a simple sample for your reference.

    class Program
        {
            static void Main(string[] args)
            {
                using (var db = new Model1())
                {
                    db.Database.Log = Console.Write;
                    IEnumerable<Blog> AllSpotted = from a in db.Blogs
                                                   where a.BlogId > 0
                                                   select a;
    
                    foreach (var item in AllSpotted)
                    {
                        Console.WriteLine(item.Name);
                    }
                    Console.ReadLine();
    
                }
            }
        }

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Sudip_inn Friday, March 16, 2018 1:18 PM
    Friday, March 16, 2018 5:41 AM
    Moderator