JCM
JCM

Reputation: 151

Translating Linq expression in c#

I am trying to convert this code:

var query2 = from b in db.MU_Reports
             join downtime in db.Downtime_Reports on b.Shift equals downtime.Shift
             where downtime.Downtime_Code.Equals("9185")
             group downtime by new { b.Date, b.Shift, b.Machine_Number, b.MU } into g
             select new
             {
                 Date = g.Key.Date,
                 Shift = g.Key.Shift,
                 Machine = g.Key.Machine_Number,
                 MU = g.Key.MU,
                 No_Work_Hours = g.Sum(x => x.Total_DownTime)
             };

To look something like this one:

var query = db.MU_Reports.Join(db.Downtime_Reports, b=> b.Shift, c=> c.Shift, (b , c) => new { b, thisshift = c })
            .Where(n => n.thisshift.Down_TIme_Codes.Equals("9185"))
            .GroupBy(d=> new { d.b.Date, d.b.Shift, d.b.Machine_Number, d.b.MU }, d => d.b)
            .Select (g=> new
            {
                Date = g.Key.Date,
                Shift = g.Key.Shift,
                Machine = g.Key.Machine_Number,
                MU = g.Key.MU,
                No_Work_Hours = g.Sum(i => i.Total_DownTime)
            }).ToList();

As you can see I am very close. My only issue is the last statement No_Work_Hours = g.Sum(i => i.Total_DownTime) It is trying to get the Total_DownTime from db.MU_Reports but it needs to come from db.Downtime_Reports. I am new to c# and am doing this to understand the program I created better.

Upvotes: 2

Views: 124

Answers (1)

juharr
juharr

Reputation: 32266

Your second argument to GroupBy should be d => d.thisshift instead of d => d.b. That corresponds to the group downtime by, but by doing d => d.b it's like you're doing group b by

var query = db.MU_Reports
    .Join(
        db.Downtime_Reports, 
        b=> b.Shift, 
        c=> c.Shift, 
        (b , c) => new { b, thisshift = c })
    .Where(n => n.thisshift.Down_TIme_Codes.Equals("9185"))
    .GroupBy(
        d=> new { d.b.Date, d.b.Shift, d.b.Machine_Number, d.b.MU }, 
        d => d.thisshift)
    .Select (g=> new
    {
        Date = g.Key.Date,
        Shift = g.Key.Shift,
        Machine = g.Key.Machine_Number,
        MU = g.Key.MU,
        No_Work_Hours = g.Sum(i => i.Total_DownTime)
    })
    .ToList();

Upvotes: 2

Related Questions