Foreach or for inside an Anynimous Type C#

Asked

Viewed 106 times

1

I am mounting a return of an Api on JSON, And the comeback I ride in Anynimoustype I believe that’s what it’s called, in it I name the variables as they go to Json, but I needed to make a foreach to return the installments, in a form of payment, as in the Example below:

//Pega as formas de pagamento do Banco de dados
        var formas = _ctx.FormasPagamento.Where(e => e.DataExclusao == null && e.EmpresaID == 1).ToList();

        //Monta o retorno em JSON usando AnynimousType
        return Json(formas.Select(e => new
        {
            e.Descricao,
            e.DiaAdicional,
            QtdParcelas = e.Parcelas,
            e.PctTaxaFinanceira,
            PrazoMedio = e.FormaPagamentoParcelas.Select(x => x.Prazo).DefaultIfEmpty(0).Sum() / e.Parcelas,
            PerPgDup = e.Parcelas / 100,

            //Aqui neste trecho seria onde eu precisava montar uma lista com as parcelas desta forma de pagamento..
            //Tentei dessa forma mas o codigo nao reconhece a operação
            ParcelasPgto = new
            {
                foreach(var forma in e.FormaPagamentoParcelas) {
                forma.Prazo,
                }
            } 

        }));

The above code does not work, and would be what I would need to do, Making Models Json serializes right, I will show an Example of the return I needed using Models, What I did not want because have to create Extra classes in the project without "Need"..

MODEL CLASSES:

public class FormaPgto
{
    public FormaPgto()
    {
        ParcelasPgtos = new List<ParcelaPgto>();
    }

    public int Id { get; set; }
    public string Descricao { get; set; }
    public int DiaAdicional { get; set; }
    public int QtdParcelas { get; set; }
    public decimal TaxaFinanceira { get; set; }
    public int PrazoMedio { get; set; }

    public int PerPgDup { get; set; }

    public List<ParcelaPgto> ParcelasPgtos { get; set; }
}

public class ParcelaPgto
{
    public int Prazo { get; set; }
}

METHOD:

 //Pega as formas de pagamento do Banco de dados
        var formas = _ctx.FormasPagamento.Where(e => e.DataExclusao == null && e.EmpresaID == 1).ToList();

        //Aqui é a classe de retorno que eu criei
        var formasRetorno = new List<FormaPgto>();

        //Percorre as formas de pagamento
        foreach (var forma in formas)
        {
            //Mapeia a classe usado como retorno para o Json serializar
            var frm = new FormaPgto();
            frm.Id = forma.ID;
            frm.Descricao = forma.Descricao;
            frm.DiaAdicional = forma.DiaAdicional;
            frm.QtdParcelas = forma.Parcelas;
            frm.TaxaFinanceira = forma.PctTaxaFinanceira;
            frm.PrazoMedio = forma.FormaPagamentoParcelas.Select(x => x.Prazo).DefaultIfEmpty(0).Sum() /
                             forma.Parcelas;
            frm.PerPgDup = forma.Parcelas / 100;

            //Percorre as parcelas da forma de pagamento, como necessitava no outro código
            foreach (var parc in forma.FormaPagamentoParcelas)
            {
                //Instancia a model da parcela
                var pct = new ParcelaPgto();
                //Mepeia
                pct.Prazo = parc.Prazo;
                //Adiciona a uma lista na forma de pagamento
                frm.ParcelasPgtos.Add(pct);
            }
            formasRetorno.Add(frm);
        }

        //Retorna em Json
        return Json(formasRetorno);

The above method with the classes I return the Json as accurate as the model below: Retorno Json Necessario

This way it works, however it has to create model classes and the work is bigger, And mapping with Aninimoustype besides giving the freedom to Define the names of the Json variables at the time of Return, discards the creation of additional classes (models) in the proejeto, just to use a return

1 answer

4


Using the Linq you can write something like the example below, to simplify...

ParcelasPgto = e.FormaPagamentoParcelas.Select(fp => new { Prazo = fp.Prazo}).ToList();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.