Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# array select

Tags:

arrays

c#

I have a bool array

a[1] = true
a[2] = false
a[3] = true
a[4] = true

how do i select only true values to a new array?

Thanks!

like image 844
Iternity Avatar asked Jan 28 '11 03:01

Iternity


2 Answers

I don't really know why you would want to do this but...

bool[] a = {true, false, true, true};
bool[] b = a.Where(x => x).ToArray();

If you just want to count how many "true"s there are:

int c = a.Count(x => x);
like image 150
Mike Avatar answered Oct 08 '22 05:10

Mike


If you mean a new array containing the indices of 'a' that had a value of true...

// Assuming here that a begins at 0, unlike your example...
Enumerable.Range(0, a.Length).Where(i=>a[i]).ToArray();
like image 36
Chris Shain Avatar answered Oct 08 '22 03:10

Chris Shain