gpt4 book ai didi

c# - 按键分组对象

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

//Car Model having Make,Model,Color 

public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public string Color { get; set; }
}

...

//List that holds the objects

List<Car> cars = new List<Car>();

cars.Add(new Car {Make = "Honda", Model = "Accord", Color = "blue"});
cars.Add(new Car {Make = "Dodge", Model = "Caravan", Color = "green"});
cars.Add(new Car {Make = "Ford", Model = "Crown Victoria", Color = "red"});
cars.Add(new Car {Make = "Honda", Model = "Civic", Color = "blue" });

我正在尝试这个

var carGroups = cars.GroupBy(c => c.Color);

List<ColorGroup> obj = new List<ColorGroup>();
foreach (var group in carGroups)
{
ColorGroup cg = new ColorGroup();
cg.Color = group.Key;

foreach (var item in group)
{
cg.cars.Add(item);
}

obj.Add(cg);
}

我需要像 json 这样的输出格式 Color 作为我的 arrayKey

{
Color:red
[
{
Make = "Honda",
Model = "Accord",
Color = "blue"
},
{
Make = "Honda",
Model = "Accord",
Color = "blue"
}
]
}

最佳答案

(使用 Json.NET)

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;

(...)

var carGroups = cars
.GroupBy(c => c.Color) // You can modify the key here: .GroupBy(c => "Color:"+c.Color)
.ToDictionary(g => g.Key);

var json = JsonConvert.SerializeObject(carGroups, Formatting.Indented);

Console.WriteLine(json);

输出

{
"blue": [
{
"Make": "Honda",
"Model": "Accord",
"Color": "blue"
},
{
"Make": "Honda",
"Model": "Civic",
"Color": "blue"
}
],
"green": [
{
"Make": "Dodge",
"Model": "Caravan",
"Color": "green"
}
],
"red": [
{
"Make": "Ford",
"Model": "Crown Victoria",
"Color": "red"
}
]
}

关于c# - 按键分组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58335810/

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