Linq groupby with where子句

时间:2013-07-22 16:19:37

标签: c# asp.net sql linq razor

我正在尝试对我的物品进行分组并包含where子句,我不太确定在哪里放置我的物品。

这是我到目前为止所拥有的:

@{
var trust = new trusteeEntities();
var gen = (from g in trust.Documents               
           where g.doc_type == "Minutes"
           orderby g.meeting_date descending
           group g by g.meeting_date into f
           select g);

    foreach (var f in gen)
    {        
       <div class="documents">   
          <span class="date">@string.Format("{0:MMMM d, yyyy}", f.meeting_date)</span> 
            <p><a href="/@f.filename">@f.title</a></p>                
       </div>        
    }   
  }  

1 个答案:

答案 0 :(得分:1)

您必须在分组后订购商品,因为GroupBy没有保留订单。而且,您选择了错误的项目。要选择群组,请使用选择f而不是选择g

from g in trust.Documents
where g.doc_type == "Minutes"   
group g by g.meeting_date into f  // Groups the items g into groups called g
orderby f.Key descending          // Orders the groups by their key (which corresponds to g.meeting_date)
select f                          // Selects the group

我还强烈建议您重命名变量:

from document in trust.Documents
where document.doc_type == "Minutes"   
group document by document.meeting_date into documentGroup  // Groups the items g into groups called g
orderby documentGroup.Key descending                        // Orders the groups by their key (which corresponds to document.meeting_date)
select documentGroup                                        // Selects the group

显示组(不确定该部分,因为我从未编写过ASP.NET代码或HTML代码):

foreach (var documentGroup in gen)
{        
   <div class="documents">   
      <span class="date">@string.Format("{0:MMMM d, yyyy}", documentGroup.Key)</span> 
      foreach (var document in documentGroup)
      {        
        <p><a href="/@document.filename">@f.title</a></p>                
      } 
   </div>        
} 

更新

鉴于foreach中的代码,我认为您不需要按日期对文档进行分组。如果是这样,Linq查询是:

from document in trust.Documents
where document.doc_type == "Minutes"   
orderby document.meeting_date descending
select document