2012-04-13 34 views
0

我想分组,并仍然检索表中的所有数据。我对Linq还很陌生,似乎无法告诉我做错了什么。我不仅想对结果进行分组,而且还想检索表格中的所有列。这可能吗?返回完整结果linq分组查询

(from r in db.Form 
    orderby r.CreatedDate descending 
    group r by r.Record into myGroup 
    where myGroup.Count() > 0 
    where (r.CreatedDate > lastmonth) 
    where r.Name == "Test Name" 
    select new { r, myGroup.Key, Count = myGroup.Count() } 
    ) 

一些如何“r”失去其上下文或自从我分组“r”它已被替换。不确定。

回答

1

您需要将任务分成两个步骤来完成你想要的。

组数据

var groupedData = db.Form.Where(item=>item.CreatedDate > lastMonth && item.Name == "Test Name") 
        .OrderByDescending(item=>item.item.CreatedDate) 
        .GroupBy(item=>item.Record) 
        .Select(group => new {Groups = group, Key = group.Key, Count = group.Count()}) 
        .Where(item => item.Groups.Any()); 

从分组数据选择Form元素

var formElements = groupedData.SelectMany(g => g.Groups).ToList(); 
+0

感谢@RePierre,它像一个魅力一样工作! – 2012-04-17 16:26:12

0

既然你个人的记录过滤,您应该分组,而不是前后进行筛选:

(
    from r in db.Form 
    where r.CreatedDate > lastMonth) 
    where r.Name == "Test Name" 
    orderby r.CreatedDate descending 
    group r by r.Record into myGroup 
    where myGroup.Count() > 0 
    select new { Groups = myGroup, myGroup.Key, Count = myGroup.Count() } 
) 
// Groups is a collection of db.Form instances 
+0

疑难杂症,所以我想,片段,现在我得到一个异常。它显示“select”语句下的错误。 无法将类型'System.Linq.IQueryable '隐式转换为'System.Collections.Generic.List '。存在明确的转换(您是否缺少演员?) – 2012-04-13 22:03:36

+1

@JasonFoglia显示您正在查询的内容。此外,最好使用'.Any()'而不是'.Count()> 0'。 – phoog 2012-04-13 23:02:47

+0

@JasonFoglia在进一步的思考中,我假设你将查询的结果分配给一个'List

'。这是行不通的,就像你发现的那样。试试这个:var list =(从db.Form中的r ...选择new {...})ToList();' – phoog 2012-04-13 23:10:35