简体   繁体   English

C#将匿名列表添加到类型列表

[英]C# add anonymous list to typed list

I am a little new to C#, sorry if the question is rudimentary. 我对C#有点陌生,很抱歉,如果这个问题很基本。

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 现金10000.00

EFT 8000.00 电汇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 结果是model.subs现在包含2个条目,但两者都相同(循环中的最后一个条目)EFT 8000.00 EFT 8000.00

What am I missing in the model.Subs.Add ? 我在model.Subs.Add中缺少什么? Or somewhere else ? 或者别的地方 ?

Move declation of subs inside of foreach loop: 在foreach循环内移动subs的小数:

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. 在您的代码中,您每次都更改相同的子对象,因此您只重复了最后一个t变量的数据。

Why don't you Select into your PaymentSubTotals instead. 您为什么不Select进入PaymentSubTotals

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. 我建议使用以下方法在每个循环上添加一个新的PaymentSubTotals对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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