gpt4 book ai didi

C# linq 组到列表中的列表

转载 作者:太空宇宙 更新时间:2023-11-03 22:30:16 25 4
gpt4 key购买 nike

我有以下类(class)

public class UserManagementClass
{
public string userID;
List<AgencyInfo> UserAgencyList;
}

public class AgencyInfo
{
public string userAgency;
public string userAgencyName;
}

现在这个列表可以有多个具有相同 userID 的实例,SQL 返回一个这样的列表:

 userID        userAgency      userAgencyName
1 5 Milk Commission
2 5 Milk Commission
2 2 Department Of CSV

我翻译成这个:

[{
"userID": "1",
"AgencyInfo": [
{
"userAgency": "5",
"userAgencyName": "Milk Commission"
}
]
},
{
"userID": "2",
"AgencyInfo": [
{
"userAgency": "5",
"userAgencyName": "Milk Commission"
}
]
},
{
"userID": "2",
"AgencyInfo": [
{
"userAgency": "2",
"userAgencyName": "Department Of CSV"
}
]
}]

如何使用 Linq 将其分组为如下所示:

 [{
"userID": "1",
"AgencyInfo": [
{
"userAgency": "5",
"userAgencyName": "Milk Commission"
}
]
},
{
"userID": "2",
"AgencyInfo": [
{
"userAgency": "5",
"userAgencyName": "Milk Commission"
},
{
"userAgency": "2",
"userAgencyName": "Department Of CSV"
}
]
}]

我尝试使用多个非查询表达式但没有成功,有人可以指出正确的方向吗?

我的林克:

var UsersList = Users.GroupBy(u => u.userID).ToList();

最佳答案

使用 GroupBy 然后使用 Select 来定义您希望如何投影分组结果。

List<UserManagementClass> UsersList = Users
.GroupBy(u => u.userID)
.Select(_ => new UserManagementClass
{
userID = _.Key,
UserAgencyList = _.SelectMany(u => u.UserAgencyList.Select(agency => agency)).ToList()
}).ToList();

关于C# linq 组到列表中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58206397/

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