将列表从一个班级复制到另一个班级的列表

时间:2018-10-18 14:54:50

标签: c# list

我正在尝试将一个列表从一个类复制到另一个类中的另一个列表。实际上有4个对象在使用。

在我看来,我正在显示带有-

的项目列表
@foreach (var item in Model.PointList)
{
     //my items displayed
}

我有一个需要Model.PointList

的列表
public partial class OrificeCert
{
 public List<OrificeCertPoint> PointList { get; set; }

}

引用OrificeCertPoint为:

public partial class OrificeCertPoint
{
    public string Total { get; set; }
    public string Raw { get; set; }
    public string Flow { get; set; }
    public string Diff { get; set; }
    public string Background { get; set; }
}

下面是另一个新列表

public partial class Temp_OrificeCert
{
    public List<Temp_OrificeCertPoints> TempPointList { get; set; }
}

引用Temp_OrificeCertPoint为:

public partial class Temp_OrificeCertPoint
{
    public string Total { get; set; }
    public string Raw { get; set; }
    public string Flow { get; set; }
    public string Diff { get; set; }
    public string Background { get; set; }
}

我的控制器中的代码是:

tempCert.TempPointList = db.Temp_OrificeCertPoints
                .Where(x => x.OrificeCertID == 1).ToList();
//one attempt
List<OrificeCertPoint> newList =   CopyTo.tempCert.TempPointList;
//another attempt
model.PointList = tempCert.TempPointList;

我已经尝试了其他几种方法,但是不断收到一条消息,提示我无法convert Temp_OrificeCertPoint to OrificeCertPoint

我需要Model.PointList来包含tempCert.TempPointList的列表

1 个答案:

答案 0 :(得分:1)

有两个不同的类,它们不能相互转换。您必须自己做:

public partial class OrificeCertPoint
{
    public string Total { get; set; }
    public string Raw { get; set; }
    public string Flow { get; set; }
    public string Diff { get; set; }
    public string Background { get; set; }

    public static OrificeCertPoint CreateFrom(Temp_OrificeCertPoint copyPoint)
    {
        return new OrificeCertPoint
        {
            Total = copyPoint.Total,
            Raw = copyPoint.Raw ,
            Flow = copyPoint.Flow,
            Diff = copyPoint.Diff,
            Background = copyPoint.Background  
        };
    }
}

现在您可以使用:

model.PointList = tempCert.TempPointList.ConvertAll(OrificeCertPoint.CreateFrom);