Enumerable.Count after Take returns Take-number instead of actual number

205 views Asked by At

I have a weird situation going on. I have following query using Devexpress XPO to MS SQL.

var _elements = (from n in new XPQuery<Elements>( XpoDefault.Session )
                 select n).Take(100);

int count =  _elements.Count();

foreach ( var e in _elements) {
     Display(e);
);

When query has 0 results Count() returns 100, but foreach statement is not executed, because enumerator yield no results.

How can I check how many rows are in query, and take only 100 records (or less)?

I don't understand why Count() returns number from take, while there no records to enumerate.

I hope that you can help me. Thanks!

1

There are 1 answers

1
SWol On

If you want to check how many rows are in query you need to execute Count() before Take(). Take returns IEnumerable, it means, that query will execute in moment, when you will execute ToList, First/FirstOrDefaut, Last/LastOrDefault etc. More information about IEnumerable