【问题标题】:How to populate a collection with new objects, copying properties from another collection如何用新对象填充集合,从另一个集合复制属性
【发布时间】:2014-11-29 15:01:06
【问题描述】:

假设我有两个类:

富:

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 都将具有NameType 来自创建它的Foo

我知道这需要看起来像这样,但不太确定如何完成它:

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
} 

请指点我正确的方向!

【问题讨论】:

  • new IEnumerable &lt;bar&gt;(); - 你不能这样做。您需要实例化一个具体类型,例如 List&lt;bar&gt;。然后你只需要在你的foreach 中做bars.Add(new bar { Name = f.Name, Type = f.Type });
  • 另外,请尝试观察C# naming conventions。如果您计划合作,它们很重要。
  • 关于命名约定的好点,我已经看到它在下面引起了混乱!休息后我正在学习编程,所以再次养成良好的习惯!

标签: c# collections ienumerable


【解决方案1】:

使用List&lt;Bar&gt; 代替IEnumerable &lt;Bar&gt;,并使用其构造函数分配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 });
}

【讨论】:

  • 这不会编译(Bar 必须是小写)
  • 现在试试这个,谢谢。会让你知道我的进展情况
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-01
    • 2023-03-21
    • 2019-10-01
    • 1970-01-01
    • 2019-08-07
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多