C# - AsEnumerable Example

前端 未结 9 1368
耶瑟儿~
耶瑟儿~ 2020-12-20 00:44

What is the exact use of AsEnumerable? Will it change non-enumerable collection to enumerable collection?.Please give me a simple example.

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-20 00:56

    Here's example code which may illustrate LukeH's correct explanation.

    IEnumerable orderQuery = dataContext.Orders
      .Where(o => o.Customer.Name == "Bob")
      .AsEnumerable()
      .Where(o => MyFancyFilterMethod(o, MyFancyObject));
    

    The first Where is Queryable.Where, which is translated into sql and run in the database (o.Customer is not loaded into memory).

    The second Where is Enumerable.Where, which calls an in-memory method with an instance of something I don't want to send into the database.

    Without the AsEnumerable method, I'd have to write it like this:

    IEnumerable orderQuery =
      ((IEnumerable)
        (dataContext.Orders.Where(o => o.Customer.Name == "Bob")))
      .Where(o => MyFancyFilterMethod(o, MyFancyObject));
    

    Or

    IEnumerable orderQuery =
      Enumerable.Where(
        dataContext.Orders.Where(o => o.Customer.Name == "Bob"),
        (o => MyFancyFilterMethod(o, MyFancyObject));
    

    Neither of which flow well at all.

提交回复
热议问题