📜  linq select count group by c#(1)

📅  最后修改于: 2023-12-03 14:43:54.184000             🧑  作者: Mango

LINQ Select Count Group By in C#

LINQ (Language Integrated Query) is a powerful tool for working with collections of data. One common task is to group data and count the number of items in each group. In this article, we will explore how to use LINQ to perform this task in C#.

Basic Syntax

The basic syntax for grouping and counting with LINQ is:

var groupCounts = from item in collection
                  group item by item.Property into g
                  select new { Property = g.Key, Count = g.Count() };

This syntax contains four parts:

  1. from: This specifies the collection to query.

  2. group: This groups the collection by a specific property.

  3. into: This creates a new collection of groups.

  4. select: This creates a new collection of objects that includes the group property and the count of items in each group.

Example

Let's assume we have a collection of Person objects, where each person has a name and a favorite color. We want to group the people by favorite color and count the number of people in each group. Here is the code to achieve this with LINQ:

public class Person
{
    public string Name { get; set; }
    public string FavoriteColor { get; set; }
}

List<Person> people = new List<Person>()
{
    new Person() { Name = "Alice", FavoriteColor = "Red" },
    new Person() { Name = "Bob", FavoriteColor = "Blue" },
    new Person() { Name = "Charlie", FavoriteColor = "Red" },
    new Person() { Name = "David", FavoriteColor = "Green" },
    new Person() { Name = "Eve", FavoriteColor = "Blue" },
    new Person() { Name = "Frank", FavoriteColor = "Red" }
};

var colorCounts = from person in people
                  group person by person.FavoriteColor into g
                  select new { Color = g.Key, Count = g.Count() };

The output of this code will be:

Color   Count
-------------
Red     3
Blue    2
Green   1
Conclusion

In conclusion, LINQ's group and count functions are a powerful way to aggregate data in a collection. By using LINQ to perform these operations, we can simplify our code and make it more readable. Hopefully, this article has given you a good starting point to using group and count in your own projects.