Using Linq as GroupBy for the objects in the list in the target

It cannot be formulated absolutely correctly, but here is what I have and here is the result that I want to achieve:

class Cake
{
public List<string> Ingrediants {get;set;}
public DateTime Baked {get;set;}
public string CakeName {get;set;}
}

List<Cake> cakes= new List<Cake>();
cakes.Add(new Cake() {CakeName = "Cake1", Ingrediants = new List<string>() {"Sugar", "Chocolate"}});
cakes.Add(new Cake() {CakeName = "Cake2", Ingrediants = new List<string>() {"Sugar", "Butter"}});
cakes.Add(new Cake() {CakeName = "Cake3", Ingrediants = new List<string>() {"Stevia", "Butter"}});

I would like to group pies using ingredients. Therefore, I would like to get the following:

 - Sugar
        Cake1
        Cake2
 - Stevia
        Cake3 
 - Chocolate
        Cake1
 - Butter
        Cake2
        Cake3

Thanks in advance!

+5
source share
3 answers

If you do not mind understanding the requests, here is an alternative (bug fixes):

IEnumerable<IGrouping<string,Cake>> query =
    from cake in cakes
    from ingredient in cake.Ingredients
    group cake by ingredient;

Surprise! This is the correct request! The language specification allows you to understand how the group ends. IGrouping<string,Cake>is technically IEnumerable<Cake>a Keytype property string- in this case an ingredient. The compiler works to turn this into almost identical code into another.

, , , into select, :

var query =
    from cake in cakes
    from ingredient in cake.Ingredients
    group cake by ingredient into cakesGrouped
    select new { Ingredient = cakesGrouped.Key, 
        Cakes = cakesGrouped.ToList() };

-, , . !

+8
var ingrediants = cakes.SelectMany(c => c.Ingrediants.Select(i => new { Cake = c, Ingrediant = i }))
    .GroupBy(ci => ci.Ingrediant)

- , - .

+6

Here is one way to do this:

var result = cakes
    .SelectMany(c => c.Ingrediants.Select(i => new
        {
            c.CakeName,
            Ingredient = i
        }))
    .GroupBy(x => x.Ingredient)
    .Select(g => new
        {
            Ingredient = g.Key,
            Cakes = g.Select(x=>x.CakeName).ToArray()
        });

resultwill be of IEnumerablean anonymous type; one element represents the ingredient and all the cakes that contain it.

+4
source

All Articles