using System.Collections.Generic;
public string? LanguageCode { get; set; }
public DateTime CreationTimestamp { get; set; }
public string? DBSHEADERPARTSK { get; set; }
public string? DBSIdentifier { get; set; }
public int DBSVersion { get; set; }
public string? Description { get; set; }
public string? InvoiceNumber { get; set; }
public Nullable<DateTime> InvoiceTimestamp { get; set; }
public string? PartNumber { get; set; }
public string? PartSerialNumber { get; set; }
public int? PartPerPackage { get; set; }
public int MfgId { get; set; }
public int LocationId { get; set; }
this.Part = new List<Part>();
public string? InvoiceNumber { get; set; }
public DateTime CreationTimestamp { get; set; }
public DateTime InvoiceTimestamp { get; set; }
public List<Part> Part { get; set; }
this.CounterSale = new List<CounterSale>();
public int LocationID { get; set; }
public string? DBSIdentifier { get; set; }
public string? DBSVersion { get; set; }
public string? InterfaceVersion { get; set; }
public string? LanguageCode { get; set; }
public List<CounterSale> CounterSale { get; set; }
public string? PartNumber { get; set; }
public string? Quantity { get; set; }
public string? Description { get; set; }
this.Location = new List<Location>();
public List<Location> Location { get; set; }
public static void Main()
var result = new List<DataClass> {
new DataClass{LocationId = 1, DBSIdentifier = "11", InvoiceNumber = "201", CreationTimestamp = now, PartNumber = "301", Description = "A"},
new DataClass{LocationId = 1, DBSIdentifier = "11", InvoiceNumber = "201", CreationTimestamp = now, PartNumber = "302", Description = "B"},
new DataClass{LocationId = 1, DBSIdentifier = "11", InvoiceNumber = "202", CreationTimestamp = now, PartNumber = "303", Description = "C"},
new DataClass{LocationId = 2, DBSIdentifier = "22", InvoiceNumber = "203", CreationTimestamp = now, PartNumber = "301", Description = "A"},
var nestedGroups = result
.GroupBy(dat => new {dat.LocationId, dat.InvoiceNumber})
.GroupBy(invGroup => invGroup.Key.LocationId)
Location = nestedGroups.Select(locGroup => new Location()
LocationID = locGroup.Key,
DBSIdentifier = locGroup.First().First().DBSIdentifier,
CounterSale = locGroup.Select(invGroup => new CounterSale()
InvoiceNumber = invGroup.Key.InvoiceNumber,
CreationTimestamp = invGroup.First().CreationTimestamp,
Part = invGroup.Select(dat => new Part()
PartNumber = dat.PartNumber,
Description = dat.Description,
var options = new JsonSerializerOptions{ WriteIndented = true };
string strJson = JsonSerializer.Serialize(root, options);
Console.WriteLine(strJson);