【问题标题】:How to Copy and Replace into List如何复制和替换到列表中
【发布时间】:2019-08-29 05:28:21
【问题描述】:

如何复制更新并替换现有列表(这将删除所有项目并替换为新类)?两个列表都已声明。

public class ProductType1
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
}

public class ProductType2
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public string ProductBarCodeNumber{ get; set; }
}

List<ProductType1> producttype1 = new List<ProductType1>()
List<ProductType2> producttype2 = new List<ProductType2>()

目的:将ProductType1全部删除,将ProductType2全部复制到ProductType1中,不包括ProductBarCodeNumber。

项目 ElectronicsStore 测试

【问题讨论】:

    标签: c# linq generics .net-core


    【解决方案1】:

    这是一个使用 Linq 投影

    的例子
    producttype1 = producttype2.Select(x => new ProductType1() 
                                                { ProductId = x.ProductId,
                                                  ProductName = x.ProductName,
                                                  ProductDescription = x.ProductDescription})
                               .ToList();
    

    【讨论】:

    • 谢谢,我认为如果 producttype1 已经有值它会删除并从 producttype2 中获取值并投影,这将起作用,感谢它
    • @JoeMiller 在所有方面都是的
    • @JoeMiller,不,投影将创建 List&lt;ProductType1&gt; 的新实例。带有productType1 的新实例。原始实例将被垃圾收集。您可以通过在投影之前将原始列表保存到临时变量来简单地检查。
    猜你喜欢
    • 1970-01-01
    • 2014-02-14
    • 2018-12-02
    • 1970-01-01
    • 2020-11-02
    • 2013-07-30
    • 1970-01-01
    • 2013-01-09
    • 2019-05-20
    相关资源
    最近更新 更多