返回完整结果linq分组查询

时间:2012-04-13 21:36:52

标签: c# 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”分组,它已被替换。不确定。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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