Linq返回分组结果

时间:2018-11-25 17:54:00

标签: c# linq lambda

我有以下数据库实体,其中包含要放在披萨上的配料。列类型是另一个表的外键,该表包含有关成分类别(奶酪,肉,蔬菜等)的信息

public class Ingredient
{
    public int IngredientId { get; set; }

    public string Name { get; set; }

    public bool IsVegetarian { get; set; }

    public int Type { get; set; }
}

一些样本数据: sample ingredients

对于每个唯一的“类型”值,我想返回具有该类型的成分列表。 最终结果将存储在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;
}

1 个答案:

答案 0 :(得分:0)

最明显的是:Ingredients = g.ToList()