Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reshape that code using foreach and initial declaration

Tags:

arrays

c#

foreach

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?

like image 214
Em1 Avatar asked Jul 13 '26 14:07

Em1


1 Answers

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.

like image 90
Marc Gravell Avatar answered Jul 15 '26 05:07

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!