English 中文(简体)
是否有办法将2个准则问题合并成一个问题?
原标题:Is there a way to combine two LINQ queries into one?
  • 时间:2012-01-12 06:58:59
  •  标签:
  • c#
  • .net
  • linq

我有一阵列,称为dbRecipes,其中包含一个分为几组的对应办法清单。 例如,Dinner群体可能有uff、ala和shed。 脱胎小组将有一个cho碎的分子。 Mmmm.

I need to display these recipes in a grouped list, such as:

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

<代码>dbRecipes中的每一项目都包含一个<>Group 的财产,其中包含关于该不动产中哪组的资料,以及一个<代码>Recipe 包含关于对应物的信息的财产。

我想用一个准则调查表对整个事物进行分类,但我远距一个准则专家,因此,我发现的最好方法是对所有不同的群体进行询问,然后通过其中每一个群体。 我的守则如下:

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

这似乎运作良好,但这样做可能提高效率、更清洁,还是需要多问? 感谢!

最佳回答
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); 
   } 
} 
问题回答

未经测试,但此处是使用<代码>的适应措施。 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);
    }
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签