A191919
A191919

Reputation: 3442

Linq add new variable in query

If i am using grouping by name:

List<Recipe> Recipes = Show.GroupBy(t => t.Name)
        .Select(g => new Recipe() { Name = g.Key, components = g.Select(t => new Component {Amount= t.Amount, Ingredient= t.Ingredient })
        .ToList() })
        .ToList();

It's write in Name value g.Key but if i want to add new variable in linq DishID how to write there DishID from DisplayRecipe?

List<Recipe> Recipes = Show.GroupBy(t => t.Name)
        .Select(g => new Recipe() { Name = g.Key,DishID= ???, components = g.Select(t => new Component {Amount= t.Amount, Ingredient= t.Ingredient })
        .ToList() })
        .ToList();

Model:

public class DisplayRecipe
{
    public string Name { get; set; }
    public string Ingredient { get; set; }
    public string Amount {get;set;}
    public int DishID { get; set; }
}

public class Recipe
{
    public string Name { get; set; }

    public int DishID { get; set; }

    public List<Component> components {get;set;}
}

public class Component
{
    public string Ingredient { get; set; }

    public string Amount { get; set; }
}

Upvotes: 1

Views: 266

Answers (2)

Kritner
Kritner

Reputation: 13765

Too long for comment (at least with example) - if you have:

Name     DishId    Components
name1    1         null
name1    2         null
name2    3         null

doing a groupby on Name, for name2, it's obvious you want DishId of 3 - but what about for name of name1?

You have to either specify which DishId to use - first, firstordefault, etc. Or rethink your group by. You may have intended to group by both fields, if name and dishid should always be grouped together.

Upvotes: 0

Yacoub Massad
Yacoub Massad

Reputation: 27861

If you group by Name only, then each group might contain items that have different DishID values.

If you want to group by both Name and DishID, then you can do it like this:

List<Recipe> Recipes =
    Show.GroupBy(t => new {t.Name, t.DishID})
    .Select(g => new Recipe()
    {
        Name = g.Key.Name,
        DishID = g.Key.DishID,
        components = g.Select(t => new Component
        {
            Amount= t.Amount,
            Ingredient= t.Ingredient
        }).ToList()
    }).ToList();

Upvotes: 2

Related Questions