Columns sorting

CSharp · Console

/Program.cs

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

    public class Section
    {
        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 class Test
{
	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"},
            };

            var result = sections
                .GroupBy(s => new {s.SectionID, s.SectionName, s.TagID, s.TagName})
                .Select(x => new
                {
                    x.Key.SectionID,
                    x.Key.SectionName,
                    x.Key.TagID,
                    x.Key.TagName,
                    SubSection = x.Count() == 1 ? null : x.Select(y => new
                    {
                        y.SubSectionID,
                        y.SubSectionName
                    }).ToArray()
                });

            var settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                Formatting = Formatting.Indented
            };
            var json = JsonConvert.SerializeObject(result, settings);
            Console.WriteLine(json);
	}
}
;