2016-03-17 58 views
1

按名称添加新的变量,如果我使用分组:中的LINQ查询

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(); 

它写在Name价值g.Key,但如果我想在LINQ DishID添加新的变量如何写有从DisplayRecipeDishID

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(); 

型号:

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; } 
} 
+2

如果两个'Recipe'对象具有相同的'Name'但不同的'DishID'会怎么样?你想使用哪种'DishID'?或者你想用“DishID”来分组吗? –

+2

什么是“显示”类型? –

回答

2

如果按Name只,然后每个组可能包含有不同的DishID值的项目。

如果您希望将双方NameDishID,那么你可以做这样的:

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(); 
0

的(至少例子)评论太长 - 如果您有:

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

做一个groupby Name,为name2,很明显你想要DishId是3 - 但的name1

您必须要么指定DishId使用 - firstfirstordefault或者通过重新思考你的小组。如果namedishid应始终组合在一起,则您可能打算按两个字段进行分组。