-1

I want to filter an IEnumerable<Product> by its productId, but I want to have all comments for the products in my result.

public class Product
{
    public int ProductId { get; set; }
    public decimal Quantity { get; set; }
    public List<ProductComments> Comments { get; set; }
}

For example: I have 3 Products

Id: 1, Quantity: 10, Comments: 2

Id: 1, Quantity: 20, Comments: 1

Id: 2, Quantity: 5, Comments: 1

What I what now is the follwing result:

Id: 1, Quantity: 30, Comments: 3 (I want the actual objects here, not just the count)

Id: 2, Quantity: 5, Comments: 1

How can I achieve this with LINQ? I think the way to go here is with GroupBy.

Thanks!

SomeBody
  • 7,515
  • 2
  • 17
  • 33
Marvin Klein
  • 1,436
  • 10
  • 33

1 Answers1

1

This will group your input as you want to:

var grouped = products.GroupBy(x => x.ProductId).Select(x => new
        {
            Id = x.Key,
            Quantity = x.Sum(y => y.Quantity),
            Comments = x.SelectMany(y => y.Comments)
        });

The code uses Sum to calculate the sum of all quantities and SelectMany to merge the comment lists into one.

Online demo: https://dotnetfiddle.net/fMNwns

SomeBody
  • 7,515
  • 2
  • 17
  • 33
  • How can I do it with an IAsyncEnumerable ? SelectMany and SelectManyAwait does not seem to work with those. – Marvin Klein Nov 30 '20 at 13:34
  • https://stackoverflow.com/questions/58376585/linq-methods-for-iasyncenumerable But actually, this is another question. You asked how to do this with a `List`. – SomeBody Nov 30 '20 at 13:40