0

我有一个布尔数组,我需要捕获元素为真的所有索引号。如何才能做到这一点?

这就是我到目前为止所拥有的

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(';');
                }

当我运行程序时 pageOneIndexLocation 的结果是这样的

  • PageOneIndexLocation {0;0;1;0;1;2;0;1;2;3;0;1;2;3} System.Text.StringBuilder

我期望的是 PageOneIndexLocation {0;1;2;4;6;7;8;10;} 这里的数字代表我的 bool 数组中所有为真的位置。

请随时告诉我哪里出错了。

4

2 回答 2

2

代替

 if (keepPageArray[i].ToString() == "True")

if (keepPageArray[i])
于 2013-06-04T14:30:34.873 回答
1

您可以使用没有循环的Lambda queryand方法来执行此操作,如下所示。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
于 2013-06-04T14:55:21.863 回答