Cutting array based on selection masks

Given two arrays:

double[] a = new double[]{1.0, 2.0, 3.0};
bool[] b = new bool[]{true, false, true};

Is there an easy way to choose abased on b? In R and other scripting languages, you say:

a[b]

to get {1.0, 3.0}. I can't figure out if there is a clean (without explicit loops) way in C # to do this. Maybe I should organize my data in a different way?

+3
source share
3 answers

You can achieve this with LINQ:

double[] a = new double[]{1.0, 2.0, 3.0}; 
bool[] b = new bool[]{true, false, true}; 
var result = a.Where((item, index)=>b[index]);
+5
source

Use the LINQ method Zip, for example:

a.Zip(b, (i, j) => new {i, j}).Where(x => x.j).Select(x => x.i)
+6
source

Also this more traditional LINQ approach:

b.Select((f, i) => f ? i : - 1).Where(i => i != -1).Select(i => a[i]);
+4
source

All Articles