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?
for(int i = 0; i < constraintValue.Length; i++)
constraintValue[i] = -1;
Count is for collections. Replace by Length for arraysThe 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
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;
}
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);