Linq Min in Select new&多个GroupBy列

时间:2015-09-15 06:20:26

标签: c# sql entity-framework linq

我想在Linq

中写下以下查询
INSERT INTO INOUTNEW (CODE,INDATE,TIME_DATE1,INOUTFLAG,TIME_FLD1,TIME_FLD2,TIME_FLD3) 
SELECT CODE,MIN(INDATE),TIME_DATE1,'I',TIME_FLD1,TIME_FLD2,'31/05/2015' FROM INOUT 
WHERE TIME_FLD1='T0003' AND INDATE >= '31/05/2015' AND INDATE <= '31/05/2015' 
AND TIME_DATE1='31/05/2015' 
GROUP BY CODE,TIME_DATE1,TIME_FLD1,TIME_FLD2

所以我正在尝试这个: -

var data = ctx.tblInOut.Where(m => m.CompanyId == companyId && m.Time_Field1 == item.ShiftCode && m.InDate == StrInStart && m.InDate <= StrInEnd && m.Time_Date1 == InputDate).Select(m =>
                            new
                            {
                                EmployeeId = m.EmployeeId,
                                InDate = Min(m.InDate),
                                Time_Date1 = m.Time_Date1,
                                InOutFlag = m.InOutFlag    
                            }).ToList();

我被困在Min部分。如何在Select中获取Min?以及如何在Linq中添加多个GroupBy

1 个答案:

答案 0 :(得分:5)

尝试这样的事情:

var data = ctx.tblInOut
.Where(m => 
    m.CompanyId == companyId && 
    m.Time_Field1 == item.ShiftCode && 
    m.InDate == StrInStart && 
    m.InDate <= StrInEnd && 
    m.Time_Date1 == InputDate
)
.GroupBy(m =>
    new {
        m.Code,
        m.Time_Date1,
        m.Time_FLD1,
        m.Time_FLD2
})
.Select(g =>
new
{
    m.Key.Code,
    InDate = m.Min(gg => gg.InDate),
    m.Key.Time_Date1,
    Something = "I",
    m.Key.Time_FLD1,
    m.Key.Time_FLD2,
    SomeDate = "31/05/2015"
}).ToList();

要获得Min,您必须先分组 - 否则它会尝试在单个元素上调用Min

.Key只是引用组的密钥(在这种情况下,代码元组,Date1,Time_FLD1,Time_FLD2)