在List c#中搜索第一个真值 [英] Search for the first true value in a List c#

查看:127
本文介绍了在List c#中搜索第一个真值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个bool列表,我想找到第一个真值的位置(第一个真值的索引)我该如何实现呢?



谢谢提前。

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.

推荐答案

尝试下面的代码:

Try with below code:
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.


除了Manas_Kumar的答案之外



In addition to Manas_Kumar's answer

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





为您提供一份清单包含所有真元素索引。

这里:{2,4}



gets you a list with all indexes of true elements.
for here: {2,4}


这篇关于在List c#中搜索第一个真值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆