Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#LINQ按如下所示格式的对象列表进行分组_C#_Linq_Group By - Fatal编程技术网

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

C#LINQ按如下所示格式的对象列表进行分组,c#,linq,group-by,C#,Linq,Group By,我有一份这种格式的数据列表- 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

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

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();
我已经做到了,我能够用上面的代码以这种格式向用户和代码展示,只是想知道如何适应这个角色,任何帮助都将不胜感激


通过创建匿名类型,可以按用户和角色进行分组。大概是这样的:

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();

按角色和用户分组,所以

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

对不起,我不明白你想要什么,你需要按用户和角色分组?我可以按我想要的格式获取用户和代码,只是不知道如何获得角色well@learner999当一个答案有8个赞成票,而另一个答案是0个,那么你可能需要考虑这一情况。你应该跳过或区别重复的<代码>代码< /代码>值。你的意思是删除第一部分?<代码> USET(D=> D代码)< /代码>返回给定代码组的所有<代码>代码< /代码>值。code>John的代码值为100101101。您的代码会打印出所有这些内容,但OP希望有
John admin 100101
。另外,我不确定您的第一个代码片段是否正确工作,它似乎会将
John
与role
admin
John
与role
review
分组,这也不是完全正确的
字符串。Join
有一个重载,它接受
IEnumerable
,因此您可以将
放到数组中
您使用的
Role=u.First()。Role
正在扼杀您答案的投票权。您假设一个用户不能属于两个或多个角色。
        result = userRoles.GroupBy(l => new {l.User,l.Role} ).Select(u => new UserRole()
        { 
            Code = string.Join(", ", u.Select(d => d.Code).Distinct().OrderBy(d => d)),
            User = u.Key.User,
            Role = u.Key.Role
        }).ToList();