Home > Blockchain >  LINQ - How to group by name from nested array
LINQ - How to group by name from nested array

Time:11-03

_id:"63624b321e78f38a3d6baf3e"
Taxes
[0] TaxName:CGST
    Amount:9.0
[1] TaxName:SGST
    Amount:8.0
_id:"63624b321e78f38a3d6baf3e"
Taxes
[1] TaxName:SGST
    Amount:8.0

I need to group by tax name and calculate Total CGST, SGST like below

CGST:9.0
SGST:16.0

I have tried to get the grouping as below. I have an object like movie summary where I added the taxes[] and tried to group by tax name. Please let me know how to do this grouping correctly.

movieSummary.Add(new DSMovieSummaryReport
                 {
                     MovieId = orderTicket.MovieId,                             
                     Taxes= orderTicket.Taxes,
                 });

var groupByTaxNamesQuery =
    from tax in movieSummary
    group tax by tax.Taxes into newGroup
    orderby newGroup.Key
    select newGroup;

CodePudding user response:

Concept: Flatten array

  1. Flatten the Taxes list to combine all the items from the lists into one list via .SelectMany().

  2. Group by TaxName.

  3. Perform total sum for Amount.

  4. Lastly, with .ToList() to materialize the query execution.

var groupByTaxNamesQuery =
            from tax in movieSummary.SelectMany(x => x.Taxes)
            group tax by tax.TaxName into newGroup
            orderby newGroup.Key
            select new { TaxName = newGroup.Key, Amount = newGroup.Sum(x => x.Amount) };

var result = groupByTaxNamesQuery.ToList();

Demo @ .NET Fiddle


Thanks to @Svyatoslav Danyliv's suggestion, you can achieve in query expression as below:

var groupByTaxNamesQuery =
            from ms in movieSummary
            from tax in ms.Taxes
            group tax by tax.TaxName into newGroup
            orderby newGroup.Key
            select new { TaxName = newGroup.Key, Amount = newGroup.Sum(x => x.Amount) };

var result = groupByTaxNamesQuery.ToList();

Demo (Full query expression) @ .NET Fiddle

CodePudding user response:

With LINQ i would have done something like :

movieSummary
    .SelectMany(m => m.Taxes)
    .GroupBy(t=>t.TaxeName)
    .Select(g=> new Taxe
    {
        TaxeName = g.Key,
        Amount = g.Sum(t => t.Amount)
    });
  • Related