4

Say I have these classes:

public class Option
{
    public int OptionID { get; set; }
    public bool IsSelected { get; set; }
}

public class Product
{
    public int ProductID { get; set; }
    public int Quantity { get; set; }
    public List<Option> Options { get; set; }
}

Let's say this would be my result after adding some Product objects into a List<Product>

2x Product 1 OptionID 1 OptionID 1 OptionID 2 OptionID 2

2x Product 1 OptionID 1 OptionID 1 OptionID 2 OptionID 2

How can I convert these results into a single result using LINQ (lambda), where IsSelected = true?

4x Product 1 4x OptionID 1 4x OptionID 2

DeMama
  • 1,134
  • 3
  • 13
  • 32
  • Your final objective isn't possible with your current `ChartItems` class. – Shaun Luttin Oct 26 '14 at 22:59
  • In your `ChartItems` class, does `Quantity` represent the quantity of a `Product` or of an `Option`? – Shaun Luttin Oct 26 '14 at 23:03
  • In your `ChartItems` class, is the `List OptionID` just a list of all selected `OptionID` values. – Shaun Luttin Oct 26 '14 at 23:05
  • 1
    -1 If you change your question after two people have provided good answers, then it's best to mark one of the answers as the correct answer to your original question, and then to ask a new question. – Shaun Luttin Oct 26 '14 at 23:15

2 Answers2

2

If I understand your question correctly, this is quite typical GroupBy:

var result = data.GroupBy(x => x.ProductID, 
                         (key, values) => new Product()
                         {
                            ProductID = key,
                            Quantity = values.Sum(p => p.Quantity),
                            Options = values.SelectMany(p => p.Options).ToList()
                         }).ToList();

so result is a List<Product> containing products merged with respect to the ProductID.

Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
1

While Konrad's answers is close, it doesn't quite provide what you're wanting. It needs to use anonymous types and two groups.

Here's a fiddle: https://dotnetfiddle.net/v907me and its most relevant code.

var query = products.GroupBy(p => p.ProductID, (key, values) => new
{
    ProductID = key, 
    Quantity = values.Sum(v => v.Quantity), 
    Options = values
        .SelectMany(v => v.Options.Where(o => o.IsSelected))
        .GroupBy(o => o.OptionID, (k, v) => new
        {
            OptionID = k,
            Quantity = v.Count()
        })
});
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
  • @DeMama While I was able to add the `IsSelected` filter, I'm not sure about what your requirements are for grafting the result into your `ChartItems` class. That part of your question is opaque to me. – Shaun Luttin Oct 26 '14 at 23:11