SO39790576

CSharp · Console

/Program.cs

using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
					
public class DatabaseAnimal {
	public int id { get; set; }	
	public string animal { get; set; }
	public string type { get; set; }
}

public class Animal {
	public Animal() {
		animalType = new List<AnimalType>();
	}
	
	public string animalDesc { get; set; }
	public List<AnimalType> animalType { get; set; }
}

public class AnimalType {
	public string typeDesc { get; set; }	
}

public class Program
{
	public static void Main()
	{
		var dbAnimal = DatabaseValues();
		
		var result = dbAnimal.GroupBy(a => a.animal)
			.Select(grp => new Animal {
				animalDesc = grp.Key,
				animalType = grp.Select(e => new AnimalType { typeDesc = e.type }).ToList()
			});
				
		Console.Write(JsonConvert.SerializeObject(result, Formatting.Indented));
	}
	
	private static IEnumerable<DatabaseAnimal> DatabaseValues() {
		yield return new DatabaseAnimal {
			id = 0,
			animal = "dog",
			type = "TypeA"
		};
		
		yield return new DatabaseAnimal {
			id = 1,
			animal = "cat",
			type = "TypeA"
		};
		
		yield return new DatabaseAnimal {
			id = 2,
			animal = "dog",
			type = "TypeB"
		};
		
		yield return new DatabaseAnimal {
			id = 3,
			animal = "cat",
			type = "TypeB"
		};
	}
}
;