簡體   English   中英

如何用新對象填充集合,從另一個集合復制屬性

[英]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都有創建時所依據的FooNameType

我知道這需要看起來像這樣,但是不太確定如何完成它:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM