HIREN
HIREN

Reputation: 15

Group Objects by Key

//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" });

I am trying this

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);
}

I need output like json format Color as Key of my array

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

Upvotes: 1

Views: 1182

Answers (3)

tmaj
tmaj

Reputation: 35037

(Using 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);

outputs

{
  "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"
    }
  ]
}

Upvotes: 2

Ihtsham Minhas
Ihtsham Minhas

Reputation: 1515

Here is another solution to the question. Using this code you can use complex groups. I also added the Ignore attributes to ignore the color property.

   static void Main(string[] args)
    {
      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);
      }
      var s = JsonConvert.SerializeObject(obj);

    }
  }
  [Serializable()]
  public class Car {
    public string Make { get; set; }
    public string Model { get; set; }
    [XmlIgnore]
    [ScriptIgnore]
    public string Color { get; set; }
  }
  public class ColorGroup {
    public ColorGroup(){
      Cars = new List<Car>();
    }
    public string Color { get; set; }
    public List<Car> Cars { get; set; }
  }

Upvotes: 0

Vivek Nuna
Vivek Nuna

Reputation: 1

You can create a dictionary of type Dictionary<string, List<Car>> by simply traversing the cars list and then serialize the dictionary to JSON string using the NewtonSoft JSON library (JSON.Net).

return JsonConvert.SerializeObject( yourDictionary );

Upvotes: 0

Related Questions