get when first time element value is null I want to add the value at that position
a[0]=0
a[1]=1
a[2]=2
a[3]=3
a[4]=null --- add 4 here
a[5]=null
a[6]=null
CodePudding user response:
try this, it was tested
var i=0;
for ( i=0; i<a.Length; i )
{
if (a[i]==null) break;
}
if(i<a.Length) a[i]=4;
CodePudding user response:
Loop through the array, check values. if you encounter null, do the thing.
for(int i = 0; i< a.Length; i )
{
if(a[i] == null)
{
// do something
// use break if you dont want to continue
break;
}
}
CodePudding user response:
It is necessary to check with the comparison operator. "your_list?=null"
CodePudding user response:
Using a foreach would not be a bad idea:
foreach (var element in a)
{
if (element is null) break; // or do something with it
}
CodePudding user response:
Loop through the array a and check for every iteration if the value in the array is null.
Example:
for(int i; i < a.Length; i ) {
if (a[i] is null) {
//Do your work here
}
}
CodePudding user response:
It is not C# related question actually. It is more about algorithms.
If talking about C#, first of all, if you are going to compare with Nulls, that means that you need to use Nullable type (e.g. int?[] in your case).
The solution is: You need to loop from the 0th element until nth-1 and at each step to compare value with Null. If Null item is at ith index, then replace a[i] with a new value and exit the cycle.
You can loop using for, foreach, or different Linq methods.