简体   繁体   English

如何用新对象填充集合,从另一个集合复制属性

[英]How to populate a collection with new objects, copying properties from another collection

Let's say I have two classes: 假设我有两节课:

Foo: Foo:

public class Foo {    
    int Id { get; set; }
    string Name { get; set; }
    string Type { get; set; }    
}

Bar: 酒吧:

public class Bar {
    string Name { get; set; }
    string Type { get; set; }
} 

So, Bar doesn't need an Id property. 因此, Bar不需要Id属性。 What I want to do is create a new collection of bar objects from an existing collection of Foo objects - there should be one Bar created for each Foo . 我想做的是从现有的Foo对象集合中创建一个新的bar对象集合-应该为每个Foo创建一个Bar Each Bar would have the Name and Type from the Foo that it was created from. 每个Bar都有创建时所依据的FooNameType

I know this will need to look something like this, but not quite sure how to complete it: 我知道这需要看起来像这样,但是不太确定如何完成它:

IEnumerable <Foo> foos = queryResults; //I'll get my foo's with a LINQ query
IEnumerable <Bar> bars = new IEnumerable<Bar>();

foreach (Foo f in foos) {
    //create a new Bar and add it to bars
} 

Please point me in the right direction! 请指出正确的方向!

您可以使用Linq查询来做到这一点:

IEnumerable <bar> bars = foos.Select(x => new bar{Name = x.Name, Type = x.Type});

Use List<Bar> instead of IEnumerable <Bar> , and assign the properties of Bar using its constructor as below 使用List<Bar>而不是IEnumerable <Bar> ,并使用其构造函数分配Bar的属性,如下所示

IEnumerable <Foo> foos = queryResults; //I'll get my foo's with a LINQ query
List<Bar> bars = new List<Bar>();

foreach (Foo f in foos) {
    bars.Add(new Bar() { Name = f.Name, Type = f.Type });
}

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

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