gpt4 book ai didi

C# LINQ 按如下所示格式的对象列表进行分组

转载 作者:行者123 更新时间:2023-12-03 19:42:54 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





C# Linq Group By on multiple columns [duplicate]

(2 个回答)



Group By Multiple Columns

(14 个回答)


去年关闭。




我有一个这种格式的数据列表 -

User    Role        Code
John admin 101
John admin 101
John admin 100
Smith superadmin 150
Smith superadmin 120
Smith superadmin 130
Smith superadmin 140
Smith superadmin 160
John review 180
John review 190
John review 200

我想根据这样的普通用户折叠它 -
 User    Role        Code
John admin 100,101
Smith superadmin 120,130,140,150,160
John review 180,190,200

我试过这个 -
result = userRoles.GroupBy(l => l.User).Select(u => new UserRole()
{
Code = string.Join(", ", userRoles.Where(d => d.User == u.Key)
.Select(d => d.Code)
.ToArray()),
User = u.Key,
}).ToList();

我已经达到了能够以上述代码的格式显示用户和代码的程度,只是想弄清楚如何适应角色,任何帮助将不胜感激。
var userRoles = new[]
{
new UserRole() { User = "John", Role = "admin", Code = "101" },
new UserRole() { User = "John", Role = "admin", Code = "101" },
new UserRole() { User = "John", Role = "admin", Code = "100" },
new UserRole() { User = "Smith", Role = "superadmin", Code = "150" },
new UserRole() { User = "Smith", Role = "superadmin", Code = "120" },
new UserRole() { User = "Smith", Role = "superadmin", Code = "130" },
new UserRole() { User = "Smith", Role = "superadmin", Code = "140" },
new UserRole() { User = "Smith", Role = "superadmin", Code = "160" },
new UserRole() { User = "John", Role = "review", Code = "180" },
new UserRole() { User = "John", Role = "review", Code = "190" },
new UserRole() { User = "John", Role = "review", Code = "200" },
};

public class UserRole
{
public string User;
public string Role;
public string Code;
}

最佳答案

您可以通过创建匿名类型按用户和角色进行分组。像这样的东西:

result = userRoles.GroupBy(l => new { l.User, l.Role }).Select(u => new
{
Code = string.Join(", ", u.Select(d => d.Code).Distinct().OrderBy(d => d)),
User = u.Key.User,
Role = u.Key.Role
}).ToList();

关于C# LINQ 按如下所示格式的对象列表进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60440863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com