c# - Using Count with Take with LINQ -


Is there a way to get a complete count when taking the operator?

You can do both.

  IEnumerable & lt; T & gt; Query = ... complex query; Int c = query.Count (); Query = query Take (n);  

Execute the count before moving it will cause the query to be executed twice, but I believe it is indispensable.

If it is in a Linq2SQL context, your comment means that it will actually double the database twice. As far as lazy is loading, it depends on how the results of the query are actually used.

For example: If you have two tables, then product and product varson where each product contains more than one < Code> Product version is connected through a foreign key

If this is your query:

  var query = db.Products.Where (P = & Gt; complex state). Orderbike (P => P. name). Then (...). Choose (P => P);  

Where you are simply selecting products , but after performing the query:

  var results = query ToList (); / / Results of query execution of forces [0]. In the context of products;  - If you refer to any foreign key or related object that was not part of the original query, then the lazy will be loaded inside. In your case, counting will not be the reason for any lazy loading because it is returning only to an int but depending on what you actually do with the result of  take ()  depends on whether you have lazy load It may or may not be sometimes difficult to say whether you are LazyLoading ocurring, to check that you should log your questions using the  DataContext.Log  property . 


Comments