c# - 按嵌套列表对列表进行分组并删除与组不对应的元素
问题描述
假设我有这样的结构(但两者A
都有B
更多的属性):
class C
{
List<A> A { get; set; }
}
class A
{
int Id { get; set; }
string Name { get; set; }
List<B> B { get; set; }
}
class B
{
int Id { get; set; }
string Name { get; set; }
int GroupId { get; set; }
}
而且我想分组B.GroupId
并只保留每个组中具有相应GroupId
值的元素。
这是一个示例数据:
[
{
"Id": 1,
"Name": "A1",
"B": [
{
"Id": 1,
"Name": "B1",
"GroupId": 1
},
{
"Id": 2,
"Name": "B2",
"GroupId": 1
},
{
"Id": 3,
"Name": "B3",
"GroupId": 2
}
]
},
{
"Id": 2,
"Name": "A2",
"B": [
{
"Id": 4,
"Name": "B4",
"GroupId": 1
},
{
"Id": 5,
"Name": "B5",
"GroupId": 2
},
{
"Id": 6,
"Name": "B6",
"GroupId": 3
}
]
}
]
作为一个resolut,我想有3组:
Group 1:
[
{
"Id": 1,
"Name": "A1",
"B": [
{
"Id": 1,
"Name": "B1",
"GroupId": 1
},
{
"Id": 2,
"Name": "B2",
"GroupId": 1
}
]
},
{
"Id": 2,
"Name": "A2",
"B": [
{
"Id": 4,
"Name": "B4",
"GroupId": 1
}
]
}
]
Group 2:
[
{
"Id": 1,
"Name": "A1",
"B": [
{
"Id": 3,
"Name": "B3",
"GroupId": 2
}
]
},
{
"Id": 2,
"Name": "A2",
"B": [
{
"Id": 5,
"Name": "B5",
"GroupId": 2
}
]
}
]
Group 3:
[
{
"Id": 2,
"Name": "A2",
"B": [
{
"Id": 6,
"Name": "B6",
"GroupId": 3
}
]
}
]
我发现我可以B.GroupId
这样分组:
from a in c
from b in a.B
group a by b.GroupId
但是我如何摆脱那些GroupId
不在相应组中的元素呢?我尝试在foreach
循环中删除它们,但这会将它们从所有组中删除,而不仅仅是一个。
解决方案
您可以尝试使用 Linq。这是“GroupBy”的示例
var jsonstring = File.ReadAllText("json1.json");
var objRoot = JsonConvert.DeserializeObject<List<A>>(jsonstring);
var result = objRoot.SelectMany(x => x.B)
.GroupBy(x => x.GroupId)
.ToDictionary(x => x.Key, y => y.ToArray());
编辑
var jsonstring = File.ReadAllText("json1.json");
var objRoot = JsonConvert.DeserializeObject<List<A>>(jsonstring);
var result = objRoot.SelectMany(AObj => AObj.B, (AObj, B) => new { AObj, B })
.GroupBy(BObj => BObj.B.GroupId)
.ToDictionary(x => x.Key, y => y.Select(y =>
new A
{
Id = y.AObj.Id,
Name = y.AObj.Name,
B = new List<B> { y.B }
}).GroupBy(x => x.Id).ToList());
Console.WriteLine(JsonConvert.SerializeObject(result));
推荐阅读
- keycloak - Keycloak 管理控制台在远程连接时需要 HTTPS(我应该禁用 SSL)
- java - 一个类的Junit测试需要其他类的对象
- laravel - 联系我们页面接收信息但没有收到消息
- php - 微小的 MCE 编辑器无法传递 textarea 内容
- android - Scan Kit 的 startScanFromFragment 方法无法按预期调用
- vue.js - 获取路由 Shopware 6 的参数
- django - 将 aws 凭据作为 windows ENV 变量传递给 dockerfile
- python-3.x - 在 Python 中查找方法的名称
- javascript - 我如何将这段 ES6 代码转换为旧版本的 javascript
- python - 将 fillna 与两个多索引数据帧一起使用会引发 InvalidIndexError