Home > other >  Is there a way to initialize a list of elements from an array and integer value?
Is there a way to initialize a list of elements from an array and integer value?

Time:04-17

I have a class called Foo with a float and Bar property.

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;

I have an array of Bar objects. I want to create a List of Foo objects that have its "Key" properties initialized to the values in the array and its "Score" values initialized to 0.

CodePudding user response:

You cannot create a list of Foo by calling barArray.ToList() since Bar and Foo are different classes, i.e you cannot cast a Bar to a Foo.

If I understand you correctly, this LINQ statement might do what you want:

List<Foo> fooList = barArray.Select(x => new Foo(x, 0.0)).ToList();

Basically, for each element in barArray, select it but create a new instance of a Foo object, pass x and 0.0 in the constructor where x is the current element from the barArray and the score is 0.0, then cast that to a list, which returns a list of Foo essentially. You'll need to add using System.Linq at the top of your code file.

  • Related