Reputation: 2263
I am trying to get the count of the items as I'm applying a query to a IQueryable.
I'am trying to do it like:
this.lblSth.Text = new Repository<Sth>().GetAll().Where(p => p.PersonId == personId).ToList().Count().ToString();
I think this gets all the data across the condition and takes the objects, then it takes the count; so I'm curious if for example I'd just take the Id columns and cast it to the list or some other smart way; that count operation would be quicker?
Info: GetAll() => It's a repository pattern method that returns IQueryable objects T from linqToSql data entity.
I'm open to all types of different ideas. Thanks
Upvotes: 2
Views: 1075
Reputation: 17680
I think the call to Where and ToList is redundant. see below.
this.lblSth.Text = new Repository<Sth>().GetAll().Count(p => p.PersonId == personId).ToString();
Upvotes: 1
Reputation: 39268
ToList() will execute the query and turn your IQUeryable into IEnumerable. I would call the count on the where clause. That way the Count will become part of the end query
Upvotes: 0
Reputation: 244928
If you want to do this quicker, just don't call ToList()
:
this.lblSth.Text = new Repository<Sth>().GetAll()
.Where(p => p.PersonId == personId)
.Count()
.ToString();
This way, (assuming it's an SQL-backed IQueryable<T>
) it will execute a query like SELECT COUNT(*) FROM …
, not SELECT * FROM …
like your approach. And this query should be much faster.
Upvotes: 1