Possible Duplicate:
How to populate/instantiate a C# array with a single value?
Given double array
double[] constraintValue = new double[UnUsedServices.Count];
I want to initialize all entry with -1
, is there a simple syntax to do it?
Possible Duplicate:
How to populate/instantiate a C# array with a single value?
Given double array
double[] constraintValue = new double[UnUsedServices.Count];
I want to initialize all entry with -1
, is there a simple syntax to do it?
double[] constraintValue = Enumerable.Repeat<double>(-1d,UnUsedServices.Count).ToArray();
for(int i = 0; i < constraintValue.Length; i++)
constraintValue[i] = -1;
double[] constraintValue = Enumerable.Repeat(-1D, UnUsedServices.Count).ToArray();
The exact answer to your question is :
for(var i =0; i < constraintValue.Length; i ++)
{
constraintValue[i] = -1;
}
However, if you want to have "unset" values, why don't you use Nullable<double>
?
double?[] constraintValue = new double?[UnUsedServices.Count];
constraintValue[10] = 42D;
constraintValue[20] = 0D;
var x1 = contraintValue[10].HasValue; // true
var x1val = contraintValue[10].Value; // 42D
var x2 = contraintValue[20].HasValue; // true
var x2val = contraintValue[20].Value; // 0D
var x3 = contraintValue[10].HasValue; // false
//var x3val = contraintValue[10].Value; // exception
you can try with
for(int i =0; i < constraintValue.Length; i ++)
{
constraintValue[i] = -1;
}
Don't know if you would call this "easy":
double[] constraintValue = new double[]{ -1, -1,
... (UnUsedServices.Count times)};
And of course, the standard way to do this is to loop over each array item to initialize it:
for(int i = 0; i < constraintValue.Length; i++)
{
constraintValue[i] = -1;
}
for (int i = 0; i < constraintValue.Length; i++)
constraintValue[i] = -1;
int[] initilize_array = newint[10];
for (int i = 0; i <initilize_array.Length; i++)
{
initilize_array[i] = -1;
}
It's the easiest way
If you need performance faster then Enumerable.Repeat do it in parallel using the TPL:
double[] constraintValue = new double[UnUsedServices.Count];
Parallel.For(0, UnUsedServices.Count, index => constraintValue[index] = -1);