Home >Database >Mysql Tutorial >How to Group and Count Data Using Entity Framework LINQ?

How to Group and Count Data Using Entity Framework LINQ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 10:52:13217browse

How to Group and Count Data Using Entity Framework LINQ?

Entity Framework Query to Group and Count Data

When working with Entity Framework, you may encounter the need to group and count data from a database. This task can be accomplished in SQL using the SELECT and COUNT statements, as demonstrated in the following query:

SELECT name, COUNT(name) FROM people
GROUP BY name

To translate this SQL statement into a Linq-Entity query, you can use either query syntax or method syntax.

Query Syntax

var query = from p in context.People
            group p by p.name into g
            select new
            {
              name = g.Key,
              count = g.Count()
            };

Method Syntax

var query = context.People
                   .GroupBy(p => p.name)
                   .Select(g => new { name = g.Key, count = g.Count() });

In both cases, the query groups the entities in the People DbSet by their name property and counts the number of entities in each group. The result is a collection of anonymous types with two properties: name and count. This result can be further processed or utilized as needed in your application.

The above is the detailed content of How to Group and Count Data Using Entity Framework LINQ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn