简体   繁体   English

返回完整结果linq分组查询

[英]Return full results linq grouping query

I'm trying to group and still retrieve all the data in the table. 我正在尝试分组并仍然检索表中的所有数据。 I'm still pretty new to Linq and can't seem to tell what I'm doing wrong. 我对Linq还是很陌生,似乎无法告诉我我做错了什么。 I not only want to group the results but I still want to retrieve all the columns in the table. 我不仅要对结果进行分组,而且还要检索表中的所有列。 Is this possible? 这可能吗?

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

Some how "r" loses its context or since I grouped "r" it has been replaced. 一些“ r”如何丢失其上下文的信息,或者由于我将“ r”分组而已被替换。 Not sure. 不确定。

You need to split your task into two steps to accomplish what you want. 您需要将您的任务分为两个步骤以完成所需的工作。

Group data 组数据

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

From the grouped data select Form elements 从分组的数据中选择Form元素

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

Since you're filtering on individual records, you should filter them before grouping rather than after: 由于要过滤单个记录,因此应在分组之前而不是之后进行过滤:

(
    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM