Lambda表达式中的GroupBy使用的正确姿势

时间:2021-12-10 16:47:45

本实例适用于:将记录中的数据进行分组得到一个一对多模型数据Model

案例中的Model

注:UserDetailes 包含User的信息和其所属部门信息

需求:将UserDetailes 的记录分组得到每个部门及其包含的用户

User:

public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
}

Dept:

public class Dept
{
public int DeptId { get; set; } public string DeptName { get; set; }
public List<User> Users { get; set; }
}

UserDetailes

public class UserDetailes
{
public int UserID { get; set; }
public string UserName { get; set; } public int DeptId { get; set; } public string DeptName { get; set; }
}

Dept提取方法:

/// <summary>
/// 模拟数据
/// </summary>
/// <returns></returns>
static List<UserDetailes> GetUser()
{
var users = new List<UserDetailes>();
for(int id=;id <=;id++ )
{
users.Add(new UserDetailes()
{
UserID = id,
UserName = "user" + id.ToString(),
DeptId = id/,
DeptName = "dept" + (id / ).ToString()
});
}
return users;
}
static void Main(string[] args)
{
var users = GetUser();
var Depts = users.GroupBy(n => new { n.DeptId, n.DeptName })
.Select(n => new Dept() {
DeptId = n.Key.DeptId,// n.key ---分组关键字段model n。分组后的集合
DeptName = n.Key.DeptName,
Users = n.Select(u => new User() {
UserID = u.UserID,
UserName = u.UserName
}).ToList() });
Console.ReadLine();
}