Reputation: 13
i would like to know how can i changes values from an array (float) depending another array (float). Example : the first array is {1,2,3,4,5,6} and the second is {0,1,0,0,1,1}. I would like the first array to show values only if the corresponding element in the second array is a "1", else "0". so the result expecting is : {0,2,0,0,5,6}.
Any help please ?
Upvotes: 1
Views: 125
Reputation: 29244
You can do it with .Zip()
in System.Linq.Enumerable
static void Main(string[] args)
{
float[] a = { 1, 2, 3, 4, 5 };
float[] b = { 0, 1, 0, 0, 1 };
float[] c = a.Zip(b, (x, y) => y == 1 ? x : 0).ToArray();
// c = {0, 2, 0, 0, 5}
}
The advantage of .Zip()
is that it can work with non numeric arrays for the condition.
public enum Respose
{
Yes,
No
}
class Program
{
static void Main(string[] args)
{
float[] a = { 1, 2, 3, 4, 5 };
Respose[] b = { Respose.No, Respose.Yes, Respose.No, Respose.No, Respose.Yes };
float[] c = a.Zip(b, (x, y) => y == Respose.Yes ? x : 0).ToArray();
// c = { 0, 2, 0, 0, 5 }
}
}
Upvotes: 0
Reputation: 8743
You can multiply each value of the first array with the value of the second array. This will result in becoming 0 when your second array is 0 and the value from your first array when your second array is 1. You can do this either with a loop:
float[] first = { 1, 2, 3, 4, 5, 6 };
float[] second = {0, 1, 0, 0, 1, 1};
float[] result = new float[first.Length];
for(int i = 0; i < first.Length; i++)
{
result[i] = first[i] * second[i];
}
Or with LINQ:
float[] first = { 1, 2, 3, 4, 5, 6 };
float[] second = {0, 1, 0, 0, 1, 1};
float[] result = first.Select((v,i) => v * second[i]).ToArray();
Don't forget to check whether your two arrays have the same length!
Upvotes: 2
Reputation: 1062820
Arrays don't hide or show anything - they are just piles of data. If you don't need to preserve the old values, you could just overwrite all the hidden data with zeros, but otherwise you'll need to do the projection yourself. This could be done when manually building a UI display, or it could be done by creating a new array that has the filtered/shown values in it; for example:
static void Main()
{
float[] values = { 1, 2, 3, 4, 5, 6 };
bool[] mask = { false, true, false, false, true, true };
var result = Filter(values, mask);
Console.WriteLine(string.Join(",", result));
}
static T[] Filter<T>(T[] values, bool[] mask)
{
var arr = new T[values.Length];
for(int i = 0; i < values.Length; i++)
{
arr[i] = mask[i] ? values[i] : default;
}
return arr;
}
Note I'm using bool
instead of float
here because float
is a bad idea for a true/false scenario. A bool[]
is also a pretty inefficient way of expressing this scenario, but... it'll do for now, for simplicity.
Upvotes: 2