有没有办法从数组和整数值初始化元素列表?
Is there a way to initialize a list of elements from an array and integer value?
我有一个名为 Foo 的 class,带有一个浮点数和一个 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 中的每个元素,select 它只是创建一个 Foo 对象的新实例,在构造函数中传递 x 和 0.0,其中 x 是 barArray 中的当前元素,得分为 0.0 ,然后将其转换为一个列表,returns 本质上是一个 Foo 列表。
您需要在代码文件的顶部添加 using System.Linq
。
我有一个名为 Foo 的 class,带有一个浮点数和一个 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 中的每个元素,select 它只是创建一个 Foo 对象的新实例,在构造函数中传递 x 和 0.0,其中 x 是 barArray 中的当前元素,得分为 0.0 ,然后将其转换为一个列表,returns 本质上是一个 Foo 列表。
您需要在代码文件的顶部添加 using System.Linq
。