gpt4 book ai didi

c# - 将 IEnumerable 对象列表转换为对象数组列表 C#

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

我有一个包含大量属性的对象模型。这些属性的值是从数据库中提取的,以提供一个 IEnumerable 列表或数组,如下所示:

var obj = context.Model.Where(x => idList.Contains(x.Id)).ToList();

这给出了这个结构中的 Json 输出 blob:

[{ Prop1: 57, Prop2: 2, Prop3: 25 ... },
{ Prop1: 23, Prop2: 4, Prop3: 20 ....},
{ Prop1: 15, Prop2: 6, Prop3: 32 ....},
... ]

有没有一种方法可以设置 linq 查询以提取这种形式的数据:

{ Prop1: [57,23,15, ...],
Prop2: [2,4,6, ....],
Prop3: [25,20,32, ...],
... }

换句话说,我想要对象数组的集合而不是对象数组

最佳答案

如果您使用的是 Json.NET,则可以使用 LINQ to JSON以完全通用的方式重构 JSON,而无需编写您自己的反射代码:

        var jArray = JArray.FromObject(obj);    // obj must serialized to an array; throw an exception otherwise.
var jObj = new JObject(jArray // Allocate new outer JSON object
.Cast<JObject>() // All array element must be json objects
.SelectMany(o => o.Properties())
.GroupBy(p => p.Name, p => p.Value) // Group all array element properties by name
.Select(g => new JProperty(g.Key, g))); // Add an array-valued property to the new outer object.
var json = jObj.ToString();
Debug.WriteLine(json);

给定以下输入 obj:

        var obj = new List<object>
{
new { Prop1 = 57, Prop2 = 2, Prop3 = 25 },
new { Prop1 = 23, Prop2 = 4, Prop3 = 20 },
new { Prop1 = 15, Prop2 = 6, Prop3 = 32 },
};

生成以下 JSON:

{"Prop1":[57,23,15],"Prop2":[2,4,6],"Prop3":[25,20,32]}

或者,如果您的 obj 是强类型的,您可以手动创建一个中间体 anonymous type对于输出,像这样:

        var newObj = new { Prop1 = obj.Select(i => i.Prop1), Prop2 = obj.Select(i => i.Prop2), Prop3 = obj.Select(i => i.Prop3) };

然后,给定以下输入 obj:

        var obj = new[] 
{
new [] { 57,2,25 },
new [] { 23,4,20 },
new [] { 15,6,32 },
}
.Select(a => new { Prop1 = a[0], Prop2 = a[1], Prop3 = a[2] });

生成相同的 JSON。

关于c# - 将 IEnumerable 对象列表转换为对象数组列表 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30140983/

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