简体   繁体   中英

C# add anonymous list to typed list

I am a little new to C#, sorry if the question is rudimentary.

I have an anonymous list as result of the following:

var Totals = model.Payments.GroupBy(pm => pm.PaymentType)
             .Select(t => new
               {
                    PaymentType = t.Key,
                    Amount = t.Sum(pm => pm.Amount)
               });

Returns Totals as anonymous list with two entries.

Cash 10000.00

EFT 8000.00

Now I need to add this list to a typed list in my viewmodel. The typed list looks like this

public class PaymentExportViewModel
{
    public List<PaymentReportViewModel> Payments { get; set; }
    public List<PaymentSubTotals> Subs { get; set; }
    public DateTime FromDate { get; set; }
    public DateTime ToDate { get; set; }
    public String VenueName { get; set;}
    public PaymentExportViewModel()
    {
        Payments = new List<PaymentReportViewModel>();
        Subs = new List<PaymentSubTotals>();
    }
}

public class PaymentSubTotals
{
    public string Type { get; set; }
    public decimal Amount { get; set; }
}

So since I need to "convert" to typed I do this

PaymentSubTotals subs = new PaymentSubTotals();
foreach (var t in Totals)
{
    subs.Type = t.PaymentType;
    subs.Amount = t.Amount;
    model.Subs.Add(subs); 
}

The result is that model.subs now contains 2 entries but both are the same (last entry in my loop) EFT 8000.00 EFT 8000.00

What am I missing in the model.Subs.Add ? Or somewhere else ?

Move declation of subs inside of foreach loop:

foreach (var t in Totals)
{
    PaymentSubTotals subs = new PaymentSubTotals();
    subs.Type = t.PaymentType;
    subs.Amount = t.Amount;
    model.Subs.Add(subs); 
}

In your code you change the same sub object every time, so you do have only the data of the last t variable, repeated.

Why don't you Select into your PaymentSubTotals instead.

var Totals = model.Payments.GroupBy(pm => pm.PaymentType)
.Select(t => new PaymentSubTotals
{
 Type = t.Key,
 Amount = t.Sum(pm => pm.Amount)
});

I would recommend the following method to add a new PaymentSubTotals object on each loop.

foreach (var t in Totals)
{
    model.Subs.Add(new PaymentSubTotals {
        Type = t.PaymentType;
        Amount = t.Amount;
    }); 
}

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