Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering two arrays to avoid Inf/NaN values

Tags:

c#

lambda

linq

I have two arrays of doubles of the same size, containg X and Y values for some plots.

I need to create some kind of protection against INF/NaN values. I need to find all that pairs of values (X, Y) for which both, X and Y are not INF nor NaN

If I have one array, I can do it using lambdas:

var filteredValues = someValues.Where(d=> !(double.IsNaN(d) || double.IsInfinity(d))).ToList();

Now, for two arrays I use the following loop:

List<double> filteredX=new List<double>();
List<double> filteredY=new List<double>();

for(int i=0;i<XValues.Count;i++)
{
   if(!double.IsNan(XValues[i]) &&
         !double.IsInfinity(XValues[i]) &&
         !double.IsNan(YValues[i]) &&
         !double.IsInfinity(YValues[i]) )
     {
       filteredX.Add(XValues[i]);
       filteredY.Add(YValues[i]);
     }
}

Is there a way of filtering two arrays at the same time using LINQ/lambdas, as it was done for the single array?

Unfortunately I can use only .NET 3.5.

like image 624
Gacek Avatar asked May 07 '10 16:05

Gacek


1 Answers

Slight correction for Mark's original answer:

var filteredValues = XValues.Zip(YValues, (x,y) => new { x, y })
        .Where(p => !(double.IsNan(p.x) || double.IsNan(p.y) || 
                      double.IsInfinity(p.x) || double.IsInfinity(p.y)))
        .ToList();

Alternatively, you might want to make it slightly neater:

Func<double, bool> valid = z => !double.IsNan(z) && !double.IsInfinity(z);
var filteredValues = XValues.Zip(YValues, (x,y) => new { x, y })
        .Where(p => valid(p.x) && valid(p.y))
        .ToList();

If you then need the results back into two lists, you can do:

var filteredX = filteredValues.Select(p => p.x).ToList();
var filteredY = filteredValues.Select(p => p.y).ToList();
like image 151
Jon Skeet Avatar answered Nov 01 '22 07:11

Jon Skeet