如何从List中获取具有特定文本的索引?

时间:2014-09-02 15:28:26

标签: c# arraylist

我有一个列表

 List<String> myArray = new List<string>()
        {
            "sometext",    /*1*/
            "desireText",  /*2*/
            "sometext",    /*3*/
            "sometext",    /*4*/
            "desireText",  /*5*/
            "desireText",  /*6*/
            "sometext",    /*7*/
            "sometext",    /*8*/
            "desireText",  /*9*/
            "sometext",    /*10*/
            "desireText",  /*11*/
            "desireText",  /*12*/
            "desireText",  /*13*/
            "sometext",    /*14*/
            "sometext",    /*15*/
            "sometext"     /*16*/
        };

我写错了代码:

List<Int32> indexes = new List<Int32>();
    for (int i = 0; i < myArray.Count; i++)
        {
            if (IsValidText(myArray[i]))
            {
                indexes.Add(i-1);
            }
        }

如何获得&#34; desireText&#34;的索引?条件: 如果后续元素相等,则仅采用第一个索引条目。 即,结果应该是:

indexes = {1,4,8,10}

1 个答案:

答案 0 :(得分:2)

您可以将条件添加到循环中:

List<Int32> indexes = new List<Int32>();
bool wasValid = false;  // flag if previous item was valid
for (int i = 0; i < myArray.Count; i++)
    {
        if (IsValidText(myArray[i]))
        {
            if (!wasValid) // previous item was not valid
                indexes.Add(i);  // note fix to keep as 0-based index 
            wasValid = true;
        }   
        else
        {
            wasValid = false;  // for next loop
        }
    }

你也可能想出一个Linq方法,但它可能更难以阅读和调试,并且不会更快。