C# 如何捕获布尔数组的索引位置
我有一个布尔数组,我需要捕获元素为真的所有索引号。如何做到这一点 这就是我目前所拥有的C# 如何捕获布尔数组的索引位置,c#,arrays,C#,Arrays,我有一个布尔数组,我需要捕获元素为真的所有索引号。如何做到这一点 这就是我目前所拥有的 bool[] keepPageArray; StringBuilder PageOneIndexLocation = new StringBuilder(50000); //Assign the bool array keepPageArray = new bool[document.Pages.Count]; // Processing is done here to give each index
bool[] keepPageArray;
StringBuilder PageOneIndexLocation = new StringBuilder(50000);
//Assign the bool array
keepPageArray = new bool[document.Pages.Count];
// Processing is done here to give each index location value of true or false
//below is where I am having difficulty
for (int i = 0; i <= keepPageArray.Length - 1; i++)
{
if (keepPageArray[i].ToString() == "True")
{
PageOneIndexLocation.Append(i);
PageOneIndexLocation.Append(';');
}
bool[]keepPageArray;
StringBuilder PageOneIndexLocation=新StringBuilder(50000);
//分配布尔数组
keepPageArray=newbool[document.Pages.Count];
//在这里进行处理,使每个索引位置值为true或false
//下面是我遇到困难的地方
对于(int i=0;i
if (keepPageArray[i].ToString() == "True")
与
替换
if (keepPageArray[i].ToString() == "True")
与
您可以使用Lambda查询
和String.Join
方法,而不使用循环,如下所示
//Example of your bool array
bool[] keepPageArray = new bool[] {true, true, true, false, true, false, true,
true, true, false,true};
//Get the index of true values
var trues = keepPageArray.Select((b, index) => new {Index = index, Val =b})
.Where(b=> b.Val)
.Select(b=> b.Index)
.ToList();
//String concatenation using Join method
string myString = string.Join(";", trues);
//Print results
Console.WriteLine(myString);
//Results: 0;1;2;4;6;7;8;10
您可以使用Lambda查询
和String.Join
方法,而不使用循环,如下所示
//Example of your bool array
bool[] keepPageArray = new bool[] {true, true, true, false, true, false, true,
true, true, false,true};
//Get the index of true values
var trues = keepPageArray.Select((b, index) => new {Index = index, Val =b})
.Where(b=> b.Val)
.Select(b=> b.Index)
.ToList();
//String concatenation using Join method
string myString = string.Join(";", trues);
//Print results
Console.WriteLine(myString);
//Results: 0;1;2;4;6;7;8;10
你能详细说明你的评论吗?你能详细说明你的评论吗?我这样做了,但结果仍然显示类似于这个页面索引位置{0;0;1;0;1;2;0;1;2}System.Text。StringBuilder@user2314840你对stringbuilder的使用是什么样子的?谢谢你,我让它工作了。它在另一个循环下运行,我没有看到。这就是为什么它增加了我的stringbuilder的计数。谢谢你,allI这么做了,但结果仍然显示类似于此PageOneIndexLocation的内容{0;0;1;0;1;2;0;1;2}System.Text。StringBuilder@user2314840你对stringbuilder的使用是什么样子的?谢谢你,我让它工作了。它是在另一个循环下运行的,我没有看到。这就是为什么它对我的stringbuilder进行计数。谢谢大家