Is there a way to combine two LINQ queries into one?

I have an array called dbRecipes that contains a list of recipes divided into groups. For example, the Dinner group may have stuffed salmon, salad and mashed potatoes. The dessert group will have chocolate molten lava cake. Mmmm.

I need to display these recipes in a grouped list, for example:

 Group 1: - Recipe 1 - Recipe 2 Group 2: - Recipe 3 

Each element in dbRecipes contains a Group property that contains information about which group it is in, and a Recipe property that contains information about the recipe.

I would like to use the LINQ query to iterate over the whole subject, but I am far from the LINQ expert, so the best way I found is to query all the individual groups and then scroll through each of them from those. Here is my code:

 var groups = (from g in dbRecipes orderby g.Group.GroupOrder select g.Group).Distinct(); foreach (var g in groups) { output.Write("{0}<br/>", g.GroupName); var recipes = (from r in dbRecipes where r.Group == g orderby r.DisplayOrder select r.Recipe); foreach(var r in recipes) { output.Write("---{0}<br/>", r.Title); } } 

This works pretty well, but is there a way to make it possibly more efficient, clean, or not requiring multiple queries? Thanks!

+4
source share
2 answers
 var groups = from r in dbRecipes orderby r.DisplayOrder group r by r.Group into g orderby g.Key.GroupOrder select g; foreach (var g in groups) { output.Write("{0}<br/>", g.Key.GroupName); foreach(var r in g) { output.Write("---{0}<br/>", r.Recipe.Title); } } 
+3
source

Unconfirmed, but adaptation using GroupBy is used here:

 var groups = dbRecipes.GroupBy(r => r.Group).OrderBy(g => g.Key.GroupOrder); foreach(var recipeGroup in groups) { output.Write("{0}<br/>", recipeGroup.Key.GroupName); foreach(var recipe in recipeGroup.OrderBy(r => r.DisplayOrder)) { output.Write("---{0}<br/>", recipe.Recipe.Title); } } 
+2
source

Source: https://habr.com/ru/post/1390590/


All Articles