Click here to Skip to main content
15,905,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I have a bool list and I want to find where the first true value lies (index of first true value) how can I achieve this?

Thanks in advance.
Posted
Comments
phil.o 26-Nov-15 7:44am    
What have you tried? Do you have problems iterating over a collection?

Try with below code:
C#
List<bool> myList = new List<bool>();
myList.Add(false);
myList.Add(false);
myList.Add(true);
myList.Add(false);
myList.Add(true);

// Get index of first element
int p = myList.IndexOf(true); // Result: 2
// Get index of last element
int p1 = myList.LastIndexOf(true); // Result: 4

// Get index of first element
int index = myList.FindIndex(a => a == true); // Result: 2
// Get index of last element
int index1 = myList.FindLastIndex(a => a == true); // Result: 4

If it helps please accept the answer.
 
Share this answer
 
v2
Comments
Member 11971544 26-Nov-15 8:24am    
Thanks this helped. But in case I have found first true condition which is: myList[2]/(int p) in your case and I want to find the next true condition. How can I go about this?
[no name] 26-Nov-15 8:28am    
Then you have to do it manually by looping over the list and find the index.
Member 11971544 26-Nov-15 8:40am    
so just in case I want to loop from the [third] item (because I have find true in the [second] item how can I do this? Thanks for the help so far.
Afzaal Ahmad Zeeshan 26-Nov-15 11:01am    
5ed.
[no name] 26-Nov-15 11:21am    
:)
In addition to Manas_Kumar's answer

C#
List<int> true_indexes = myList.Select((value, index) => value ? index : -1).Where(o => o >= 0).ToList();


gets you a list with all indexes of true elements.
for here: {2,4}
 
Share this answer
 
Comments
BillWoodruff 26-Nov-15 20:50pm    
+5 nice use of Linq and ?: operator !

You could also write this solution using the 'projection' aspect of Linq Select where you use the 'new operator:

var trueIndexes = myList
.Select((value, index) => new {value, index})
.Where(x => x.value)
.ToList();

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900