[英]How to populate a collection with new objects, copying properties from another collection
假設我有兩節課:
Foo:
public class Foo {
int Id { get; set; }
string Name { get; set; }
string Type { get; set; }
}
酒吧:
public class Bar {
string Name { get; set; }
string Type { get; set; }
}
因此, Bar
不需要Id屬性。 我想做的是從現有的Foo
對象集合中創建一個新的bar
對象集合-應該為每個Foo
創建一個Bar
。 每個Bar
都有創建時所依據的Foo
的Name
和Type
。
我知道這需要看起來像這樣,但是不太確定如何完成它:
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
}
請指出正確的方向!
您可以使用Linq
查詢來做到這一點:
IEnumerable <bar> bars = foos.Select(x => new bar{Name = x.Name, Type = x.Type});
使用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.