I have a problem in using list in the loops and I appreciate if any of you guys can help me.
I want to create a list and populating it from array (named in my code: sarray) with the values bigger than -999. But the problem is when the values are less than -999, the code dumps the previous items of the list and the size instead of being 40, is 27 (as if new list list is created)!
List<double> nums = new List<double>();
for (int i = 0; i < 50; i++)
{
if (sarray[i] > -999)
{
nums.Add(sarray[i]);
}
}
these are the values:
[31411.0857 31411.0902 31411.0847 31411.0858 31411.0859 31411.0479 31411.0649 31411.0895 31411.0944 31411.0207 31411.0683 31411.0717 31411.075 31411.0825 -999 -999 -999 -999 -999 -999 -999 -999 -999 -999 31411.0156 31411.0718 31411.0719 31411.0884 31411.0885 31411.0936 31411.0896 31411.0897 31411.0537 31411.066 31411.0661 31411.0556 31411.0701 31411.0731 31411.0952 31411.0716 31411.0776 31411.0803 31411.091 31411.0911 31411.0919 31411.0919 31411.0919 31411.0919 31411.0919 31411.0919 ]
The generic list takes an enumerable in one of its overloaded constructors, and you can use the Linq
Whereextension method to constrain the items to add:You state that
-999represents a “null” value for you, in that case you could change theWhereto not assume the valid values are greater than -999:I believe this style expresses the intent more clearly than crafting your own loops.
As an aside,
double.NaNmight be a more obvious representation of an invalid value.This is because you are only checking where values are greater than -999:
if (sarray[i] > -999)However, the value dump you provided doesn’t have any items that are less than -999 so this check will suffice – so long as the data set remains the same.