Linq Select的最大值/最小值,左连接

时间:2018-07-27 21:57:49

标签: linq

我正在尝试将程序从ADO转换为Entity Framework和Linq。有人可以告诉我如何使用Linq编写此代码吗?

map(response => new NmChatRequest(response[0]))

我已经接近了,但是我没有得到分组和最大/最小部分...

SELECT a.[Category], [WorkOrderVersion], min(a.[CategoryStartDate]) AS CategoryStartDate, 
       max(a.[CategoryEndDate]) AS CategoryEndDate, c.[HexColor] AS CustomBackgroundColor
FROM [Job].[EstimateTbl] as a
Left JOIN [Employee].[EmployeeColorPrefsTbl] c 
     ON c.[Item] = a.[Category] AND c.[EmployeeID] = @employeeID
Where [ID_Job] = @ID_Job 
group by [Category], [WorkOrderVersion], c.[HexColor] 
ORDER BY [Category]

2 个答案:

答案 0 :(得分:1)

var query = (from a in db.EstimateTbls.Where(x=>x.ID_Job==objActiveJobClass.ID)
            join c in db.EmployeeColorPrefsTbls.Where(x=>x.EmployeeID==@employeeID)
                 on a.Category equals c.Item 
            into ps1
            from ps in ps1.DefaultIfEmpty()
            select new{a,ps}).ToList()
            .GroupBy(x=>new{x.a.Category,x.a.WorkOrderVersion,HexColor=x.ps?.HexColor})
            .Select(x=>new
                       {
                        Category=x.Key.Category,
                        WorkOrderVersion=x.Select(z=>z.a.WorkOrderVersion).FirstOrDefault(),
                        CategoryStartDate=x.Min(z=>z.a.CategoryStartDate),
                        CategoryEndDate=x.Max(z=>z.a.CategoryEndDate),
                        CustomBackgroundColor=x.Key.HexColor
                       })
            .OrderBy(x=>x.Category)
            .ToList();

答案 1 :(得分:0)

var query = from a in db.EstimateTbls
                        where a.ID_Job == objActiveJobClass.ID
                        join c in db.EmployeeColorPrefsTbls on a.Category equals c.Item 
                        group new { a, c} by new { a.Category, a.WorkOrderVersion, a.CategoryStartDate, a.CategoryEndDate, c.HexColor } into g
                        orderby g.Key.Category ascending, g.Key.WorkOrderVersion
                        select new
                        {
                            Count = g.Count(),
                            g.Key.Category,
                            g.Key.WorkOrderVersion,
                            g.Key.CategoryStartDate,
                            g.Key.CategoryEndDate,
                            CustomBackgroundColor = g.Key.HexColor,

                        };

APP.1(2)7/26/2018 12:00:00 AM,7/31/2018 12:00:00 AM,#FFFFA500

CAB.1(6),,#FF00FF00

CLN.1(126),,#FF7FFFD4

DMO.1(5)8/1/2018 12:00:00 AM,8/5/2018 12:00:00 AM,#FFFF0000

DMO.2(1)8/5/2018 12:00:00 AM,8/10/2018 12:00:00 AM,#FFFF0000