简体   繁体   中英

Linq C# Sum in Group By

I'm trying to transform the SQL that is here http://sqlfiddle.com/#!6/a1c8d/2 in linq below. The expected result is what is in sqlfiddle, but my LINQ returns more rows.

PS: In sqlfiddle the fields are reduced to not increase pollution and stay focused on my problem.

resultado.Dados =
    (
        from a in db.AgendaHorario
        join b in db.Agenda on a.AgendaID equals b.AgendaID                            
        select new 
        {
            a.AgendaID,
            Horario = a.Horario,
            Controle = a.Controle,
            Cor = b.Cor,
            Agenda = b.Sigla                            
        }).AsEnumerable()
        .GroupBy(g => new 
        {          
            g.AgendaID,
            Horario = g.Horario.ToString("dd/MM/yyyy"), 
            Data = g.Horario.ToString("yyyy-MM-dd"),
            g.Controle,
            g.Agenda,
            g.Cor
        })                        
        .Select(s => new
        {
            id = s.Key.AgendaID,
            title = s.Key.Agenda,                             
            start = s.Key.Data,                            
            color = String.IsNullOrEmpty(s.Key.Cor) ? "3a87ad" : s.Key.Cor,
            className = "",
            someKey = 1,
            allDay = false,                            
            Resultado0 = s.Sum(m => m.Controle == "L" ? 1 : 0).ToString(),
            Resultado1 = s.Sum(m => m.Controle == "B" ? 1 : 0).ToString()                             
        });

As per the comments, this addresses the question of how to repeat your SqlFiddle in Linq. Note that the projection to a String Date cannot be converted to Sql directly, so I've had to early materialize with AsEnumerable() (obviously, in your real query, apply any filters prior to materializing!). You could probably do the grouping on just the date part using SqlFunctions , eg 3 x applications of SqlFunctions.DatePart will allow you to group by dd, MM and YYYY

var dados = db.AgendaHorarios1
  .AsEnumerable()
  .GroupBy(ah => ah.Horario.ToString("dd/MM/yyyy"))
  .Select(g => new {Horario = g.Key, 
                    Livre = g.Count(x => x.Controle == "L"),
                    Bloq = g.Count(x => x.Controle == "B"),
                    Aged = g.Count(x => x.Controle == "A")});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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