New classes for the loop

I currently have the following code:

DecisionVariable[] attributes = { new DecisionVariable("Var1", 2), new DecisionVariable("Var2", 4), new DecisionVariable("Var3", 1), new DecisionVariable("Var4", 2), new DecisionVariable("Var5", 5), }; 

but I would like to create them using a For loop:

  DecisionVariable[] attributes = { for (int i=0;i<49;i++) { new DecisionVariable ("Var" + i, iValues[i]); } }; 

In the second version, C # tells me that "For" has an invalid expression.

Do I have a typo somewhere or something like this is not allowed at all using the for loop in the constructor?

+7
source share
5 answers

You cannot use a for loop inside a collection initializer. Use this code instead:

 DecisionVariable[] attributes = new DecisionVariable[49]; for (int i = 0; i < 49; i++) attributes[i] = new DecisionVariable ("Var" + i, iValues[i]); 
+12
source
  DecisionVariable[] attributes = new DecisionVariable[49]; for (int i=0; i<49; i++) { attributes[i] = new DecisionVariable("Var" + i, iValues[i]); } 

You can also use generics and do:

  List<DecisionVariable> attributes = new List<DecisionVariable>(); for (int i=0; i<49; i++) { attributes.Add(new DecisionVariable("Var" + i, iValues[i])); } 
+3
source

You can use the LINQ syntax for this:

 DecisionVariable[] attributes = Enumerable. Range(0, 49). Select(i => new DecisionVariable("Var" + i, iValues[i])). ToArray(); 
+3
source

It is convenient to use the Enumerable.Range Method :

 DecisionVariable[] attributes = Enumerable .Range(0, 49) .Select(i => new DecisionVariable("Var" + i, iValues[i])) .ToArray(); 

If the iValues array has the same number of elements that you would like to have for the attributes array, then consider the following code:

 DecisionVariable[] decisionVariables = iValues .Select((value, index) => new DecisionVariable("Var" + index, value)) .ToArray(); 
+1
source

You can do something like this.

 Class1[] c1 = new Class1[12]; for (int i = 0; i < 12; i++) { c1[i] = new Class1(i); } 
0
source

All Articles