Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a select count group by SQL query in LINQ?

Tags:

linq-to-sql

I have this query which works but when I try to write the equivalent in LINQ I get the incorrect SQL produced.

My query is:

SELECT COUNT(*)
FROM tableName
GROUP BY ColumnId

I've tried writing it as:

tableName.GroupBy(x => x.ColumnId).Count()

But looking in LINQPad it is producing the SQL:

SELECT COUNT(*) AS [value]
FROM (
SELECT NULL AS [EMPTY]
FROM [tableName] AS [t0]
GROUP BY [t0].[ColumnId]
) AS [t1]

What am I doing wrong? Thanks!

like image 709
Kevin Avatar asked Jan 26 '11 14:01

Kevin


People also ask

How do you write a count query in LINQ?

Count() methodIEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" }; // Will return 4 int result = strings. Count(); NOTE: The Count() LINQ method (an extension method to IEnumerable<T> ) is slightly different from the Count property on List<T> .

How can we do a GroupBy using LINQ query?

You can also use Into Group with GroupBy in VB.Net. LINQ query is ended with the help Select or Groupby clause. It can also support method syntax in both C# and VB.Net languages. As shown in example 2.

Can count be used with GroupBy?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

How do I group count in C#?

EMP. GroupBy(p => p. departmentname) select new { count = p. Count(), p.


1 Answers

Your LINQ query is counting the number of groups but your SQL query is producing the counts by group. You want

var counts = tableName.GroupBy(x => x.ColumnId)
                      .Select(g => new { g.Key, Count = g.Count() });

to get the counts by group.

Note that if you want exactly the same SQL you want

var counts = tableName.GroupBy(x => x.ColumnId)
                      .Select(g => g.Count());

The first example above should be a little more useful as it gives the ids of each group as well.

like image 87
jason Avatar answered Oct 22 '22 00:10

jason