当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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!

网友答案:
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); 
   } 
} 
网友答案:

Untested, but here is an adaptation using GroupBy:

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);
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: