cyrus
cyrus

Reputation: 1356

LINQ group items into lists in anonymous type, with duplicates

I have 3 boxes that can contain fruit:

A - apples, oranges, pears

B - apples, bananas

C - pears

I'd like to create a LINQ query statement that generates a new anonymous type that groups the boxes by the fruit they contain (not actual code):

fruitBoxes.apples = {A, B}
fruitBoxes.oranges = {A}
fruitBoxes.bananas = {B}
fruitBoxes.pears = {A, C}

Upvotes: 0

Views: 965

Answers (2)

Enigmativity
Enigmativity

Reputation: 117064

You could do this:

var boxes = new []
{
    new { box = "A", fruit = new [] { "apples", "oranges", "pears", }, },
    new { box = "B", fruit = new [] { "apples", "bananas", }, },
    new { box = "C", fruit = new [] { "pears", }, },
};

var query =
    from b in boxes
    from f in b.fruit
    group b.box by f into bs
    select new
    {
        fruit = bs.Key,
        boxes = bs.ToArray(),
    };

The result I get it this:

result

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

All anonymous type properties have to be known at compile time, so unless you know exactly what fruits you're going to deal with (which is unlikely) you can't use anonymous types.

You can use Dictionary<string, List<string>> instead:

var result = boxes.SelectMany(b => b.Fruits.Select(f => new { Box = b, Fruit = f }))
                  .GroupBy(x => x.Fruit, x => x.Box.Name)
                  .ToDictionary(g => g.Key, g => g.ToList());

Box is defined as:

class Box
{
    public string Name { get; set; }
    public List<string> Fruits { get; set; }
}

Upvotes: 2

Related Questions