开发者

Check next string in the list

Trying to figure out how to check the next string vs. the current string in a loop (pseudo code):

string currentName = string.Empty;

for(int i=0; i < SomeList.Count; i++)
{
    currentName = SomeList[i].Name;

    //do some other logic here

    if(string.Compare(SomeList[i].Name, SomeList[i+1].Name) == 0)
         // do something
}

this does not seem to work:

if(string.Compare(SomeList[i].Name, SomeList[i+1].Name)

I want to see if the current string is the same as what the next string in the loop before it开发者_JAVA技巧 gets to the next iteration in the loop.


You are close. You will get an IndexOutOfRangeException when you get to the last element because you are attempting to check the following element (inherently, there is none).

Just change

for(int i=0; i < SomeList.Count(); i++)

to

for(int i=0; i < SomeList.Count() - 1; i++)


It's probably throwing an IndexOutOfRangeException, isn't it? You have to watch your boundary case at the upper end:

if (i != SomeList.Count - 1 && 
    string.Compare(SomeList[i].Name, SomeList[i+1].Name) == 0) 
{
    // Do something
}


I would suggest that you bump the index counter to start at 1, and do the comparison to SomeList[i-1], SomeList[i] so that you don't get an IndexOutOfRangeException.

Also, this is case sensitive matching, call the ToUpper() method to ensure to do case insensitive matching.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜