In LINQ (Language Integrated Query), the "group by" clause is used to group elements based on a specific key or property. It is primarily used in query expressions to perform grouping operations on data.
The "group by" clause allows you to group data based on a common attribute or property and create a sequence of groups, where each group contains elements that share the same key. It is similar to the "GROUP BY" clause in SQL.
Here's a basic syntax of the "group by" clause in LINQ:
var query = from item in collection
group item by item.Property into groupedItems
select new
{
Key = groupedItems.Key,
Items = groupedItems
};
In this example, collection
is the data source from which you want to group elements, and Property
is the common attribute or property based on which you want to group them. The groupedItems
variable represents each group, and you can access the key of the group using the Key
property.
You can also apply aggregate functions like Count
, Sum
, Average
, etc., to perform calculations on the grouped elements. Additionally, you can use the into
keyword to create a new range variable (groupedItems
in the example) that represents the group, and then perform further operations on the grouped data.
Here's an example that demonstrates grouping a list of objects by a property and calculating the average of another property within each group:
var groupedData = from item in collection
group item by item.Category into groupedItems
select new
{
Category = groupedItems.Key,
AveragePrice = groupedItems.Average(item => item.Price)
};
In this example, the objects in the collection
are grouped by the Category
property, and then the average price of items in each category is calculated using the Average
method.
The "group by" clause is a powerful feature in LINQ that allows you to perform complex grouping and aggregation operations on data, making it easier to analyze and manipulate collections of objects.
Comments
Post a Comment