using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
public int SectionID { get; set; }
public string SectionName { get; set; }
public int? SubSectionID { get; set; }
public string SubSectionName { get; set; }
public int? TagID { get; set; }
public string TagName { get; set; }
public static void Main()
var sections = new List<Section>
new Section { SectionID = 1, SectionName = "Section 1", SubSectionID = null, SubSectionName = null , TagID = 1, TagName = "Tag 1"},
new Section { SectionID = 2, SectionName = "Section 2", SubSectionID = null, SubSectionName = null , TagID = 2, TagName = "Tag 2"},
new Section { SectionID = 3, SectionName = "Section 3", SubSectionID = 1 , SubSectionName = "SubSection 1", TagID = 3, TagName = "Tag 3"},
new Section { SectionID = 3, SectionName = "Section 3", SubSectionID = 2 , SubSectionName = "SubSection 2", TagID = 3, TagName = "Tag 3"},
new Section { SectionID = 3, SectionName = "Section 3", SubSectionID = 3 , SubSectionName = "SubSection 3", TagID = 3, TagName = "Tag 3"},
new Section { SectionID = 4, SectionName = "Section 4", SubSectionID = null, SubSectionName = null , TagID = 2, TagName = "Tag 2"},
new Section { SectionID = 5, SectionName = "Section 5", SubSectionID = null, SubSectionName = null , TagID = 1, TagName = "Tag 1"},
.GroupBy(s => new {s.SectionID, s.SectionName, s.TagID, s.TagName})
SubSection = x.Count() == 1 ? null : x.Select(y => new
var settings = new JsonSerializerSettings
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented
var json = JsonConvert.SerializeObject(result, settings);