I have to set a property which expects to get an array hence I need an array of instances of class X, as follow:
X[] x = new X[]
{
new X () { Parameter = parameter },
new X () { Parameter = parameter2 }
// ...
}
Since the parameter are generated while runtime and stored in a list, the instances should be created dynamically. I get my intended aim with that code
X[] x = new X[list.Count];
for (int i = 0; i < list.Count; i++)
{
x[i] = new X() { Parameter = list.ElementAt(i) }
}
These lines do their job, however, I'm not satisfied with these lines. I'd like to change some things, i.e. code which looks like that Pseudo-Code
X[] x = new X[]
{
foreach (var item in list)
{
new X () { Parameter = item }
}
}
This code, however, will not work. Is there a way to implement such a code?
How about:
X[] x = list.Select(param => new X { Parameter = param }).ToArray();
Here, .Select(...) creates a projection, i.e. a sequence that for every item in the list performs the new X {...} operation; the .ToArray() converts that sequence to an array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With