Linq groups and fetches the max id

3

Is there any way to optimize the code below so that you search for the forms that are at the maximum version according to IdCentroCusto ?

In the code below I'm doing the grouping and getting the CM.Max(d => d.Versao) to fetch the correct form.

var Formularios = qrFormularios
                       .GroupBy(F => new { F.IdCentroCusto, F.Versao })
                       .Select(CM => new
                       {
                           Formulario = qrFormularios.FirstOrDefault(n => n.Versao == CM.Max(d => d.Versao) && n.IdCentroCusto == CM.Key.IdCentroCusto),
                       })
                       .ToList();

I would need a query that would return all the form fields.

[Serializable, Table("tb_Formularios")]
    public partial class rtb_Formularios 
    {
        [Key]
        public Int32 IdFormulario { get; set; }
        public Int32 IdModFormulario { get; set; }
        [MaxLength(100)]
        public String TituloFormulario { get; set; }
        public Int32 Vigencia { get; set; }
        public Int32 IdUsuario { get; set; }
        public Int32 IdCentroCusto { get; set; }
        public Int32 Versao { get; set; }
        public Int32? IdLogStatus { get; set; }
        public Int32 IdPassoWorkflow { get; set; }
        public DateTime? DtTransmisao { get; set; }
        public DateTime DtInclusao { get; set; }
        [Timestamp]
        public Byte[] SeqAlteracao { get; set; }

        [NotMapped]
        public Int32 PKValue
        {
            get { return IdFormulario; }
        }
    } 
    
asked by anonymous 07.12.2015 / 18:52

1 answer

5

Marconcilio, you can first make a subquery to return the most recent Version of each cost center ... then you join with this subquery.

var centrosCusto = 
    from formulario in qrFormularios
    group formulario.Versao by formulario.IdCentroCusto into grupo
    select new { 
        IdCentroCusto = grupo.Key, 
        Versao = grupo.Max(versao => versao)
    };

var formularios = (
    from formulario in qrFormularios
    join centroCusto in centrosCusto on new { formulario.IdCentroCusto, formulario.Versao } equals new { centroCusto.IdCentroCusto, centroCusto.Versao }
    select formulario;
).ToList();
    
07.12.2015 / 19:57