C# Group By

C# Group By

LINQ (language integrated query)

A query expression can return the results as groups. With the group by operators in the C# language, we separate the results of an expression into groups. This makes some query expressions more effective.

Example

Note

The group by clause comes at the end of a query expression; no select clause is required in query expressions that use group by. The first part of group by indicates what item is to be grouped, and after the by operator, you specify the condition that results in groups.

Here, IsEven returns true or false for every number; some numbers are grouped in the "false" category and the rest are grouped in the "true" category.

Odd and Even Numbers
Program that uses group by operators [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Input array.
	int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

	// Group elements by IsEven.
	var result = from element in array
		     orderby element
		     group element by IsEven(element);

	// Loop over groups.
	foreach (var group in result)
	{
	    // Display key and its values.
	    Console.WriteLine(group.Key);
	    foreach (var value in group)
	    {
		Console.WriteLine(value);
	    }
	}
    }

    static bool IsEven(int value)
    {
	return value % 2 == 0;
    }
}

Output

False
1
3
5
7
9
True
2
4
6
8
Foreach loop construct

Using result. Probably the hardest part of using group by is knowing how to access its results. First, you can use foreach to enumerate the groups themselves. On each group, you can access the Key property. Finally, when you use foreach to enumerator on the group, you can get the values.

Tip:More information on foreach is available on this site.

Foreach Loop Examples

Summary

The C# programming language

The group by clause is an alternative to the select clause in query expressions. It allows you to divide the results in any number of categories, which can simplify further logic in your program. It can be useful for creating sitemaps or other tree-like hiearchies.

转自:http://www.dotnetperls.com/group

### C# 中 `GroupBy` 方法的使用教程与示例 #### 基本概念 `GroupBy` 是 LINQ 提供的一个强大工具,用于按照指定键对数据集中的元素进行分组。此方法返回一个 `IGrouping<TKey, TElement>` 的序列,其中每个对象都代表一组具有相同键的数据项。 #### 多列分组实例 当需要基于多个字段来进行分组操作时,可以创建匿名类型的组合键作为分组依据: ```csharp var query = from p in people group p by new { p.Country, p.City } into g select new { CountryCity = g.Key, PeopleCount = g.Count() }; foreach (var item in query) { Console.WriteLine($"{item.CountryCity.Country},{item.CountryCity.City}:{item.PeopleCount}"); } ``` 上述代码展示了如何通过两个属性(国家和地区)来对人员列表进行分组,并统计每组的人数[^1]。 #### 条件分组实例 除了简单的按单个或多个字段分组外,还支持更复杂的逻辑判断以动态定义分组标准: ```csharp var conditionGroups = people.GroupBy(p => p.Age > 25 ? "Older" : "Younger"); foreach (var group in conditionGroups) { Console.WriteLine($"Group: {group.Key}"); foreach (var person in group) { Console.WriteLine($" {person.Name}, {person.Age}"); } } ``` 这段代码实现了根据不同年龄段将人群分为两部分:“年长者”和“年轻人”,并打印出各组成员的信息[^2]。 #### 设备类型分组实例 对于特定领域内的实体类,比如表示不同种类设备的对象集合,则可以根据其类别属性轻松完成分类整理工作: ```csharp var groups = devices.GroupBy(d => d.Type); foreach (var group in groups) { Console.WriteLine(group.Key); foreach (var device in group) { Console.WriteLine( $"ID:{device.Id}," + $"Name:{device.Name}," + $"Type:{device.Type}," + $"Result:{device.Result}" ); } } ``` 这里展示了一个针对设备记录表执行分组查询的过程,最终输出了每一类别的所有条目详情[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值