linq - Linq query of of two objects with nested array
问题描述
I have two objects pulled from from two separate JSON files. One is the source, the other is a reference to look up specific data from the source.
Source JSON:
{
"options": [
{
"id": 1,
"product_id": 1,
"size": "S",
"color": "red"
},
{
"id": 2,
"product_id": 1,
"size": "M",
"color": "red"
},
{
"id": 3,
"product_id": 1,
"size": "L",
"color": "red"
},
{
"id": 4,
"product_id": 1,
"size": "XL",
"color": "red"
},
{
"id": 5,
"product_id": 1,
"size": "S",
"color": "blue"
},
{
"id": 6,
"product_id": 1,
"size": "M",
"color": "blue"
},
{
"id": 7,
"product_id": 1,
"size": "L",
"color": "blue"
},
{
"id": 8,
"product_id": 1,
"size": "XL",
"color": "blue"
}
]
}
Lookup JSON:
{
"product": {
"styles": [
{
"color": "red",
"options": [1,2,3,4]
},
{
"color": "blue",
"options": [5,6,7,8]
}
]
}
}
Both are deserialized to C# models.
I need to get a list of distinct sizes across all options, so I'm querying like so:
var sizes = (from o in options
from s in product.styles
from ss in s.optionIds
where ss == o.id
select new Size
{
name = v.size,
optionIds = // needs to be an array with all option ids
}
).ToList().GroupBy(ps => ps.name).Select(ps => ps.First()).ToList();
The from/where section works as expected and I get a list or distinct sizes, however, I also need to list all option ids in the new Size object...see comment in code.
The result array I'm expecting:
[
{
"name": "S",
"optionIds": [1,5]
},
{
"name": "M",
"optionIds": [2,6]
},
{
"name": "L",
"optionIds": [3,7]
},
{
"name": "XL",
"optionIds": [4,8]
}
]
解决方案
据我所知,您的“查找 JSON”不包含源中尚未找到的任何信息,因此用这些数据混淆水是没有意义的。
var sizes = options
.GroupBy(o => o.size, o => o.id)
.Select(g => new Size {name = g.Key, options = g.ToList()})
.ToList()
推荐阅读
- regex - 如何为 AWS 资源制作正则表达式
- ios - Flutter iOS Firebase Analytics 和 Crashlytics 未显示
- c - 如何在 CUnit 的帮助下测试自定义错误消息?
- javascript - 通过数据ID引用使javascript更改选择选项
- excel - Having problems copying an Excel range to a Word file using VBA
- javascript - 读取服务器上的表单数据
- firebase - 无法从 createUserWithEmailAndPassword 的 firebase 响应访问 stsTokenManager
- java - 如何在JAVA中替换对象属性中的特殊字符
- shell - 实际有效的 CygWin 替代方案
- swift - 如何将具有关联类型的协议与 ObservableObject 一起使用?