c# - 使用 LINQ 扁平化嵌套结构
问题描述
我收到一个包含嵌套列表的 JSON 有效负载。可以使用 LINQ 来扁平化结构并将嵌套列表拉出为非规范化形式吗?
我有强大的数据库背景,所以这就是为什么我称它为 JSON 数据的非规范化形式。
我以前使用过 LINQ,但没有使用这些深度类型的结构。
我尝试使用 LINQ fluent 方法,但似乎无法访问嵌套列表
public class Exampleobject
{
public string result { get; set; }
public Propertydata propertyData { get; set; }
}
public class Propertydata
{
public List<Buildings> building { get; set; }
}
public class Buildings
{
public string itemId { get; set; }
[JsonProperty("type")]
public string buildingType { get; set; }
public string buildingTypeCode { get; set; }
public string buildingTypeDescription { get; set; }
[JsonProperty("floors")]
public List<floorInvolved> floorsInvolved { get; set; }
}
public class floorInvolved
{
public string InvolvedId { get; set; }
public List<FRole> roles { get; set; }
}
public class FRole
{
public string code { get; set; }
public string description { get; set; }
}
Sample Data:
{
"result": "200 OK",
"propertyData": {
"building": [
{
"itemId": "9A85B1CCBD65C1F2",
"type": "V",
"buildingTypeCode": "02",
"buildingTypeDescription": "mixed space",
"floors": [
{
"InvolvedId": "04",
"roles": [
{
"code": "OFF",
"description": "Office space"
},
{
"code": "APT",
"description": "Apartment"
},
{
"code": "STG",
"description": "Storage"
}
]
},
{
"InvolvedId": "05",
"roles": [
{
"code": "OFF",
"description": "Office space"
},
]
}
],
}
]
}
}
I'm trying to get the building bubbled up with the details like this:
ID Description Floor Role
9A85B1CCBD65C1F2 mixed space 04 Office space, Apartment, Storage
9A85B1CCBD65C1F2 mixed space 05 Office space
I load the json data like so
var resulting = JsonConvert.DeserializeObject<Exampleobject>(rawjson);
解决方案
使用查询语法:
var result =
from building in resulting.propertyData.building
from floor in building.floorsInvolved
select $"{building.itemId} {building.buildingTypeDescription} " +
$"{floor.InvolvedId} " +
$"{string.Join(", ", floor.roles.Select(role => role.description))}";
或者(也许更易读):
var result =
from building in resulting.propertyData.building
from floor in building.floorsInvolved
let roles = floor.roles.Select(role => role.description)
select $"{building.itemId} {building.buildingTypeDescription} " +
$"{floor.InvolvedId} {string.Join(", ", roles)}";
使用扩展方法语法:
var result = resulting.propertyData.building
.SelectMany(building => building.floorsInvolved
.Select(floor => $"{building.itemId} {building.buildingTypeDescription} " +
$"{floor.InvolvedId} " +
$"{string.Join(", ", floor.roles.Select(role => role.description))}"));
推荐阅读
- node.js - 如何修复我的 app.js 文件中的 API 版本控制代码?
- sql - 根据行拆分记录
- react-native - 如何从 TabBar react-native 隐藏已经存在的标题栏
- java - 获得平均值
- reactjs - 解析失败 SyntaxError:输入意外结束
- c++ - 多次创建相同的对象名称是否很好c ++
- kubernetes - kubernetes 找出 pod 中哪个容器崩溃
- android - 无论如何要获得recyclerview项目的拖放事件的持续时间吗?
- visual-studio-code - Visual Studio Code - 可以对“打开编辑器”面板进行排序吗?
- python - 带有字段增量的Odoo Cron?