[英]Return item 1 to 3 and 4 to 6 and 7 to 9 in a grouped object with LINQ
[英]Linq Return grouped result
我有以下數據庫實體,其中包含要放在披薩上的配料。 列類型是另一個表的外鍵,該表包含有關成分類別(奶酪,肉,蔬菜等)的信息
public class Ingredient
{
public int IngredientId { get; set; }
public string Name { get; set; }
public bool IsVegetarian { get; set; }
public int Type { get; set; }
}
一些樣本數據: 樣本成分
對於每個唯一的“類型”值,我想返回具有該類型的成分列表。 最終結果將存儲在IngredientViewModel類型的ICollection中。
public class IngredientViewModel : Model
{
public IngredientCategory Category { get; set; }
public List<Ingredient> Ingredients { get; set; }
}
我怎樣才能最好地使用linq或lambda表達式在單個數據庫行程中按類別對所有成分進行分組?
我目前有以下代碼段,有些混亂:
public async Task<IEnumerable<IngredientViewModel>> GetIngredientsPerCategoryAsync()
{
IEnumerable<Ingredient> result = await _repo.GetAllAsync();
IEnumerable<IngredientViewModel> viewModels = result.GroupBy(
x => x.Type,
(category, ingredients) => new IngredientViewModel()
{
Category = (IngredientCategory)category,
Ingredients = MapFromEntities(ingredients)
})
.OrderBy(x => x.Category.ToString())
.ToList();
return viewModels;
}
最明顯的是: Ingredients = g.ToList()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.