C#将匿名列表添加到键入列表

时间:2017-02-08 15:52:43

标签: c# .net asp.net-mvc

我对C#有点新意,对不起,如果这个问题还不成熟。

我有一个匿名列表,其结果如下:

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

将Totals作为包含两个条目的匿名列表返回。

现金10000.00

EFT 8000.00

现在我需要将此列表添加到viewmodel中的类型列表中。键入的列表如下所示

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; }
}

因为我需要“转换”为打字我执行此操作

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

结果是model.subs现在包含2个条目,但两者都是相同的(我的循环中的最后一个条目) EFT 8000.00 EFT 8000.00

我在model.Subs.Add中缺少什么?或者别的地方 ?

3 个答案:

答案 0 :(得分:2)

在foreach循环内移动sub的declation:

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

在您的代码中,每次都更改相同的子对象,因此您只有重复的最后一个t变量的数据。

答案 1 :(得分:2)

为什么不让In file included from /home/testuser/testproject/external.h:26:0, from /home/testuser/testproject/main.cpp:14: /home/testuser/externallib/Object.h: In instantiation of ‘int ObjectImpl<T_Class, T_Type, T_Size>::addChild(IObj*, unsigned int) [with T_Class = Shape; ObjType T_Type = (ObjType)12u; unsigned int T_Size = 20u: /home/testuser/externallib/Object.h:1618:43: required from here /home/testuser/externallib/Object.h:817:5: note: declarations in dependent base ‘ObjBase’ are not found by unqualified lookup /home/testuser/externallib/Object.h:817:5: note: use ‘this->get_Obj’ instead 代替你Select

PaymentSubTotals

答案 2 :(得分:1)

我建议使用以下方法在每个循环上添加一个新的PaymentSubTotals对象。

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