[英]How do I copy one list to another that has an object with additional properties in C# ? (without a foreach)
I have the need to copy one list of objects into another, however, the second list has additional properties (basically, the first list is a subset of the second list).我需要将一个对象列表复制到另一个列表中,但是,第二个列表具有其他属性(基本上,第一个列表是第二个列表的子集)。 Here's an example of how to do with a foreach loop for a class Product and another class ProductExt that inherits from product and adds another property to it.
下面是一个如何处理 class 产品和另一个 class ProductExt 的 foreach 循环的示例,该产品继承自产品并向其添加另一个属性。 -- this is an abbreviated version of what I need to do --
-- 这是我需要做的一个简略版本 --
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
//note there are 78 more product properties!
}
public class ProductExt : Product
{
public int FirstVariantId { get; set; }
}
And an example of how it's done with a foreach (but I'd like to do this in Linq but not really sure how to go about it):以及如何使用 foreach 完成的示例(但我想在 Linq 中执行此操作,但不确定如何使用 go 来解决它):
List<Product> products = new List<Product>();
products.Add(new Product { Id = 1, Name = "widget a" });
products.Add(new Product { Id = 2, Name = "widget b" });
products.Add(new Product { Id = 3, Name = "widget c" });
products.Add(new Product { Id = 4, Name = "widget d" });
products.Add(new Product { Id = 5, Name = "widget e" });
products.Add(new Product { Id = 6, Name = "widget f" });
products.Add(new Product { Id = 7, Name = "widget g" });
List<ProductExt> productExts = new List<ProductExt>();
// want to copy products into productExts list with a default value of 0 for FirstVariantId
foreach(var p in products)
{
var px = new ProductExt();
px.Id = p.Id;
px.Name = p.Name;
px.FirstVariantId = 0;
productExts.Add(px);
}
Is there a way to do this in Linq (with the default value)?有没有办法在 Linq (使用默认值)中做到这一点?
Try this:尝试这个:
List<ProductExt> productExts = products.select(product=> new ProductExt()
{
Name = product.Name,
// another properties
}).Tolist();
If you don't assign value to any property, the default value set to that property.如果您不为任何属性赋值,则将默认值设置为该属性。 ( Example: For int properties => 0 )
(示例:对于 int 属性 => 0)
You can always use AutoMapper for these type of work.您始终可以将AutoMapper用于这些类型的工作。 The benefit would be that you wouldn't need to remember mapping new properties if you add new ones later.
这样做的好处是,如果您稍后添加新属性,则无需记住映射新属性。
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Product, ProductExt>();
});
var mapper = config.CreateMapper();
List<ProductExt> productExts = products.Select(p => mapper.Map(p, new ProductExt())).ToList();
Ok, it looks like Mapster is the winner here - it's very fast and simple.好的,看起来 Mapster 是这里的赢家 - 它非常快速和简单。
List<ProductExt> productExts = new List<ProductExt>();
products.Adapt(productExts);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.