GroupBy与Linq to实体查询

时间:2016-02-17 11:42:10

标签: c# entity-framework group-by linq-method-syntax

我有以下课程:

public class OrderItem
{
     public int Id { get; set; }
     public ICollection<NominalRouting> NominalRoutings{ get; set; }
}
public class NominalRouting
{
     public int Id { get; set; }
     public DateTime PlanedDate {get; set;} //yyyy/mm/dd
     public virtual Operation Operation{ get; set; }
}
public class Operation 
{
     public int Id { get; set; }
     public string Code { get; set; }
     public virtual AreaSpecification AreaSpecification{ get; set; }
}
public class AreaSpecification 
{
     public int Id { get; set; }
     public string Title { get; set; }
}

我有以下数据:

-----------------------------------------------------------
| OrderItemId |  AreaTitle | Operation Code | PlannedDate |
-----------------------------------------------------------
|      1      |    Area1   |       OP1       | 2016/01/01 |
|      1      |    Area1   |       OP2       | 2016/01/02 |
|      1      |    Area1   |       OP3       | 2016/01/03 |
|      1      |    Area2   |       OP4       | 2016/02/01 |
|      1      |    Area2   |       OP5       | 2016/02/02 |
|      1      |    Area3   |       OP6       | 2016/03/01 |
|      1      |    Area3   |       OP7       | 2016/03/04 |
|      1      |    Area3   |       OP7       | 2016/03/08 |
-----------------------------------------------------------

如何首先使用EF代码将linq写入实体(方法语法)查询,GroupBy将数据写入AreaTitle以上数据并获得以下结果(每个{{earlear PlannedDate AreaTitle 1}}):

-----------------------------------------------------------
| OrderItemId |  AreaTitle | Operation Code | PlannedDate |
-----------------------------------------------------------
|      1      |    Area1   |       OP1       | 2016/01/01 |
|      1      |    Area2   |       OP4       | 2016/02/01 |
|      1      |    Area3   |       OP6       | 2016/03/01 |
-----------------------------------------------------------

2 个答案:

答案 0 :(得分:2)

我没有看到任何特别的东西 - 小组,订购每个小组的元素并先拿走。

查询语法会更清晰,但这里是方法语法查询:

var query = db.OrderItems
    .SelectMany(orderItem => orderItem.NominalRoutings)
    .GroupBy(routing => routing.Operation.AreaSpecification.Title)
    .Select(g => new
    {
        AreaTitle = g.Key,
        Routing = g.OrderBy(e => e.PlanedDate).FirstOrDefault()
    })
    .Select(e => new
    {
        e.Routing.OrderItem.Id,
        e.AreaTitle,
        e.Routing.Operation.Code,
        e.Routing.PlanedDate
    });

答案 1 :(得分:1)

这个怎么样:

var result = myList.GropuBy(x => x.AreaTitle).Select(x => 
    {
        var first = x.OrderBy(y => y.PlannedDate).First();
        return new 
        { 
            OrderItemId = first.OrderItemId,
            AreaTitle = x.Key,
            OperationCode = first.Operation Code,
            PlanedDate = first.PlanedDate 
        }
    });