我有一个名为 Foo 的类,它有一个 float 和 Bar 属性。
public class Bar
{
//Contains Stuff
}
public class Foo
{
public Foo(Bar _key, float _score)
{
Bar = _key;
Score = _score;
}
public Bar Key;
public float Score;
}
Bar[] barArray = new Bar[10];
List<Foo> fooList = barArray.ToList() //Where this would initialize the List with 10 Foo elements
// each with the respective Bar object from the array and
//a value of 0.0 for their Score;
我有一组 Bar 对象。我想创建一个 Foo 对象列表,其“Key”属性初始化为数组中的值,其“Score”值初始化为 0。
您不能通过调用 barArray.ToList() 创建 Foo 列表,因为 Bar 和 Foo 是不同的类,即您不能将 Bar 转换为 Foo。
如果我对您的理解正确,则此 LINQ 语句可能会执行您想要的操作:
List<Foo> fooList = barArray.Select(x => new Foo(x, 0.0)).ToList();
基本上,对于 barArray 中的每个元素,选择它但创建一个 Foo 对象的新实例,在构造函数中传递 x 和 0.0,其中 x 是 barArray 中的当前元素并且分数为 0.0,然后将其转换为一个列表,这本质上返回一个 Foo 列表。您需要using System.Linq
在代码文件的顶部添加。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句