I have an array called dbRecipes which contains a list of recipes divided into groups. For example, the Dinner group might have a stuffed salmon, a salad, and mashed potatoes. The dessert group would have a chocolate molten lava-cake. Mmmm.
I need to display these recipes in a grouped list, such as:
Group 1:
- Recipe 1
- Recipe 2
Group 2:
- Recipe 3
Each item in dbRecipes contains a Group property which contains information about which group it’s in, and a Recipe property which contains information on the recipe.
I’d like to use a LINQ query to iterate through the whole thing, but I’m far from a LINQ expert so the best way I’ve found is to query for all the distinct groups, then loop through each one of those. Here’s 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 seems to work fairly well, but is there a way to do this that’s perhaps more efficient, cleaner, or doesn’t require multiple queries? Thanks!
1 Answer