【问题标题】:Linq groupby with where clause带有 where 子句的 Linq groupby
【发布时间】:2013-07-21 11:35:25
【问题描述】:

我正在尝试对我的项目进行分组并包含一个 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>        
    }   
  }  

【问题讨论】:

  • 而不是select g 使用select f
  • @lazyberezovsky 在哪里?
  • 尝试使用文本搜索:)

标签: c# asp.net sql linq razor


【解决方案1】:

您必须在分组后订购物品,因为GroupBy 不保持顺序。此外,您选择了错误的项目。要选择组,请使用 select f 而不是 select 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

【讨论】:

  • 我的 for 语句中不包含“meeting_date”的定义并且没有扩展方法
  • 好的,我明白为什么了。在这种情况下,为什么需要对文档进行分组?您不想按日期对它们进行排序吗?
  • 我需要对它们进行分组,以便特定日期的文档列在该日期下
  • 但是您没有使用foreach 中的组。
  • 我将如何在 foreach 中使用它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多