Linq Return grouped result












0















I have the following database entity containing ingredients to put on pizza. Column Type is a foreign key to another table containing information on the ingredient category (cheese, meat, vegetables etc.)



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

public string Name { get; set; }

public bool IsVegetarian { get; set; }

public int Type { get; set; }
}


Some sample data:
sample ingredients



For each unique 'Type' value, I want to return a List of Ingredients with that type.
The final result will be stored in an ICollection of type IngredientViewModel.



public class IngredientViewModel : Model
{
public IngredientCategory Category { get; set; }

public List<Ingredient> Ingredients { get; set; }
}


How can I best get all ingredients, grouped per category in a single database trip using linq or lambda expressions?



I currently have the following snippet which I find a bit messy:



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









share|improve this question

























  • stackoverflow.com/q/7325278

    – Robert Harvey
    Nov 25 '18 at 17:55











  • What have you tried you so far, and where did you get stuck?

    – Yogu
    Nov 25 '18 at 17:55
















0















I have the following database entity containing ingredients to put on pizza. Column Type is a foreign key to another table containing information on the ingredient category (cheese, meat, vegetables etc.)



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

public string Name { get; set; }

public bool IsVegetarian { get; set; }

public int Type { get; set; }
}


Some sample data:
sample ingredients



For each unique 'Type' value, I want to return a List of Ingredients with that type.
The final result will be stored in an ICollection of type IngredientViewModel.



public class IngredientViewModel : Model
{
public IngredientCategory Category { get; set; }

public List<Ingredient> Ingredients { get; set; }
}


How can I best get all ingredients, grouped per category in a single database trip using linq or lambda expressions?



I currently have the following snippet which I find a bit messy:



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









share|improve this question

























  • stackoverflow.com/q/7325278

    – Robert Harvey
    Nov 25 '18 at 17:55











  • What have you tried you so far, and where did you get stuck?

    – Yogu
    Nov 25 '18 at 17:55














0












0








0








I have the following database entity containing ingredients to put on pizza. Column Type is a foreign key to another table containing information on the ingredient category (cheese, meat, vegetables etc.)



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

public string Name { get; set; }

public bool IsVegetarian { get; set; }

public int Type { get; set; }
}


Some sample data:
sample ingredients



For each unique 'Type' value, I want to return a List of Ingredients with that type.
The final result will be stored in an ICollection of type IngredientViewModel.



public class IngredientViewModel : Model
{
public IngredientCategory Category { get; set; }

public List<Ingredient> Ingredients { get; set; }
}


How can I best get all ingredients, grouped per category in a single database trip using linq or lambda expressions?



I currently have the following snippet which I find a bit messy:



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









share|improve this question
















I have the following database entity containing ingredients to put on pizza. Column Type is a foreign key to another table containing information on the ingredient category (cheese, meat, vegetables etc.)



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

public string Name { get; set; }

public bool IsVegetarian { get; set; }

public int Type { get; set; }
}


Some sample data:
sample ingredients



For each unique 'Type' value, I want to return a List of Ingredients with that type.
The final result will be stored in an ICollection of type IngredientViewModel.



public class IngredientViewModel : Model
{
public IngredientCategory Category { get; set; }

public List<Ingredient> Ingredients { get; set; }
}


How can I best get all ingredients, grouped per category in a single database trip using linq or lambda expressions?



I currently have the following snippet which I find a bit messy:



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






c# linq lambda






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 16:02







Michiel Wouters

















asked Nov 25 '18 at 17:54









Michiel WoutersMichiel Wouters

3916




3916













  • stackoverflow.com/q/7325278

    – Robert Harvey
    Nov 25 '18 at 17:55











  • What have you tried you so far, and where did you get stuck?

    – Yogu
    Nov 25 '18 at 17:55



















  • stackoverflow.com/q/7325278

    – Robert Harvey
    Nov 25 '18 at 17:55











  • What have you tried you so far, and where did you get stuck?

    – Yogu
    Nov 25 '18 at 17:55

















stackoverflow.com/q/7325278

– Robert Harvey
Nov 25 '18 at 17:55





stackoverflow.com/q/7325278

– Robert Harvey
Nov 25 '18 at 17:55













What have you tried you so far, and where did you get stuck?

– Yogu
Nov 25 '18 at 17:55





What have you tried you so far, and where did you get stuck?

– Yogu
Nov 25 '18 at 17:55












1 Answer
1






active

oldest

votes


















0














The most obvious would be: Ingredients = g.ToList().






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53470269%2flinq-return-grouped-result%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    The most obvious would be: Ingredients = g.ToList().






    share|improve this answer




























      0














      The most obvious would be: Ingredients = g.ToList().






      share|improve this answer


























        0












        0








        0







        The most obvious would be: Ingredients = g.ToList().






        share|improve this answer













        The most obvious would be: Ingredients = g.ToList().







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 25 '18 at 18:39









        MartyMarty

        1846




        1846






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53470269%2flinq-return-grouped-result%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

            Calculate evaluation metrics using cross_val_predict sklearn

            Insert data from modal to MySQL (multiple modal on website)