1

I tried to take only 1000 entities from about 7000. When Queryable converted to list, it is more then 1000 entities returned.

IQueryable<MyEntity> query = {some query};
query = query.Take(1000);
var cnt = query.Count();  // 1000
var list = query.ToList();  // 1217
var listId = query.Select(x => x.Id).ToList();  // 1000

How is it possible? Query is simple enough, just like _context.MyEntities.Where();

  • When you convert Query to a HashSet (not a List), how much items does the collection have? If it has more than '1000' entries, it is taking more than it should. If it is taking only 1000, it is taking duplicates. Let me know you answer, i'll dig deeper into it once I have your answer :-) – THEoneANDonly Sep 02 '20 at 21:02
  • How are you observing the sizes? Linq queries are notoriously tricky when viewing in the debugger due to filtering iterators, deferred execution, etc. What does `list.Count` give you? – D Stanley Sep 02 '20 at 21:08
  • What you says makes no sense. ToList() will never lose elements from original query. – Zuabros Sep 02 '20 at 21:17
  • @THEoneANDonly HashSet has also 1217 items. Actually, there are no dublicates by the Key. Maybe it's worth to know, data provider is DB View. – Artem Tsukanov Sep 03 '20 at 09:39
  • @DStanley `list.Count` gives the same number 1217. – Artem Tsukanov Sep 03 '20 at 09:43
  • Can you post what is inside Entity? maybe highlight relationships – THEoneANDonly Sep 03 '20 at 09:47
  • @THEoneANDonly Finally, solved by adding `.OrderBy(x => x.Id)` just before `.Take(n)`. The problem was that somehow EF6 builds some queries without Top (n) in the first Select statement. – Artem Tsukanov Sep 03 '20 at 11:24
  • Does this answer your question? [LINQ .Take() returns more elements than requested](https://stackoverflow.com/questions/11983208/linq-take-returns-more-elements-than-requested) – Arsen Khachaturyan Sep 03 '20 at 15:38

0 Answers0