49

How can I write LINQ to SQL with COUNT?

Example:

var purch = from purchase in myBlaContext.purchases
            select purchase;

How can I get the count here?

2 Answers 2

91

Like that

var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();

or even easier

var purchCount = myBlaContext.purchases.Count();
Sign up to request clarification or add additional context in comments.

5 Comments

@Bside: lblCount.Text = myBlaContext.purchases.Count().ToString()
@George Duckett, thank you. but i got the error: CS0103: The name 'lblCount' does not exist in the current context ... and i put lblCount on the aspx page...
@Bside: Depending on where on the page you put it, you might not be able to access it like that. This is a seperate question really now: how to access a control on an asp.net page. See msdn.microsoft.com/en-us/library/ms178509(v=vs.90).aspx
@Anrei Are there any performance differences if we use myBlaContext.purchases.Count() vs (from purchase in myBlaContext.purchases select purchase.ID).Count()
@irvgk, I suspect there might be. Actually you can use any sql profile you'd like to check the resulting sql query that linq generates, even for such similar queries it might differ. I will do that myself when I have a chance (not on windows at the moment)
10

You should be able to do the count on the purch variable:

purch.Count();

e.g.

var purch = from purchase in myBlaContext.purchases
select purchase;

purch.Count();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.